猫鼬模式要求数组可以为空 [英] Mongoose schema to require array that can be empty
问题描述
我有这个模式
var StuffSchema = new mongoose.Schema({
_id: { type: String, required: true, unique: true },
name: { type: String, required: true }
});
mongoose.model('Stuff', StuffSchema);
工作正常.
现在我需要添加另一个包含此内容的架构"Cargo"
Now I need to add another schema "Cargo" containing this
mystuff: { type:[String], ref: 'Stuff', required:true},
也就是说,我希望mystuff包含Stuff的ID数组,但这在运行此代码时失败,并显示验证错误
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...)
如果我在mystuff字段中使用了一个空数组. 如果将Cargo模式更改为
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'},
但是我希望mystuff字段是必需的,并允许空数组
but I want the mystuff field to be required and allow empty arrays
我该怎么做才能做到这一点?
What can I do to make this happen?
推荐答案
默认情况下会创建空数组(另请参见源代码).您可以删除该属性以获得所需的行为.
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.
(此外,猫鼬为所有模式分配一个默认的_id
字段,其类型为ObjectId.声明它是不必要的,虽然肯定允许使用字符串,但这不是典型的.)
(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.)
编辑2017年11月:这是Mongoose 5的候选更改.请参见 https://github.com/Automattic/mongoose/issues/5139 .
Edit Nov 2017: This is a candidate change in Mongoose 5. See https://github.com/Automattic/mongoose/issues/5139.
这篇关于猫鼬模式要求数组可以为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!