Mongoose schema to require array that can be empty

*爱你&永不变心* 提交于 2019-12-22 03:42:24

问题


I have this schema

var StuffSchema = new mongoose.Schema({
    _id: { type: String, required: true, unique: true },
    name: { type: String, required: true }
});

mongoose.model('Stuff', StuffSchema);

Works fine.

Now I need to add another schema "Cargo" containing this

mystuff: { type:[String], ref: 'Stuff', required:true},

that is, I want mystuff to contain array of ids of Stuff, but this fails with validation error when running this code

mongoose.model('Cargo').create( some data...)

if I use an empty array for the mystuff field. It seems to work if I change the Cargo schema to

mystuff: { type:[String], ref: 'Stuff'},

but I want the mystuff field to be required and allow empty arrays

What can I do to make this happen?


回答1:


Empty arrays are created by default (see also this). The attribute required: true requires the array to have at least one element in it (source code). You can remove that attribute to get your desired behavior.

(Aside, mongoose assigns a default _id field with the type ObjectId to all schemas. Declaring it is unnecessary, and using a string is not typical, although certainly allowed.)

Edit Nov 2017: This is a candidate change in Mongoose 5. See https://github.com/Automattic/mongoose/issues/5139.



来源:https://stackoverflow.com/questions/27268172/mongoose-schema-to-require-array-that-can-be-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!