【发布时间】:2021-05-21 06:14:08
【问题描述】:
我有一组代表文件夹的对象。我想让用户根据需要创建文件夹,并限制应用程序将创建一个“根”文件夹(对象),并且我想控制这个文件夹的 _id 属性。根据mongoDB documentation,我应该可以设置 _id 字段,但是当我尝试时出现错误:
Cast to ObjectId failed for value "0" at path "_id"
mongo 文档说 _id 可以是数组以外的任何 BSON data type,所以我不明白为什么“0”无效。为什么我不能使用 '0' 作为 _id?
明确地说,我希望 mongoDB 为根文件夹以外的所有其他情况生成一个 id。
文件夹架构:
const mongoose = require('mongoose');
const constants = require('../config/constants');
const { Schema } = mongoose;
const FolderSchema = new Schema(
{
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: [true, 'Folder must have a user'],
},
name: {
type: String,
required: true,
trim: true,
},
dateCreated: {
type: Date,
default: Date.now,
},
lastUpdated: {
type: Date,
default: Date.now,
},
parentId: {
type: String,
required: true,
},
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
},
);
FolderSchema.index({ name: 'text' });
// eslint-disable-next-line func-names
FolderSchema.virtual('id').get(function () {
return this._id.toHexString();
});
module.exports = mongoose.model('Folder', FolderSchema);
【问题讨论】:
-
您能否包含模型的架构?
-
@caffeinated.tech 完成