【问题标题】:Mongoose schema to require array that can be emptyMongoose 模式需要可以为空的数组
【发布时间】:2015-01-31 19:21:25
【问题描述】:

我有这个架构

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

mongoose.model('Stuff', StuffSchema);

工作正常。

现在我需要添加另一个包含此的模式“货物”

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

也就是说,我希望 mystuff 包含 Stuff 的 id 数组,但是在运行此代码时失败并出现验证错误

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

如果我对 mystuff 字段使用空数组。 如果我将 Cargo 模式更改为

,它似乎可以工作
mystuff: { type:[String], ref: 'Stuff'},

但我希望 mystuff 字段是必需的并允许空数组

我该怎么做才能做到这一点?

【问题讨论】:

    标签: arrays validation mongoose required


    【解决方案1】:

    默认情况下会创建空数组(另请参阅this)。 required: true 属性要求数组中至少包含一个元素 (source code)。您可以删除该属性以获得所需的行为。

    (除此之外,mongoose 为所有模式分配了一个 ObjectId 类型的默认 _id 字段。声明它是不必要的,并且使用字符串不是典型的,尽管当然允许。)

    2017 年 11 月编辑:这是 Mongoose 5 中的候选更改。请参阅 https://github.com/Automattic/mongoose/issues/5139

    【讨论】:

    • 我不认为模式类型 必须 是 ObjectId,它必须是所引用模式的标识符属性的类型。请参阅文档中的示例mongoosejs.com/docs/populate.html
    • 正如您所建议的,自 Mongoose 版本 5 以来,默认行为已更改。引用 mongoosejs.com/docs/migrating_to_5.html#array-required : > 在 mongoose 5 中,required 验证器仅验证值是否为数组。也就是说,它不会像在 mongoose 4 中那样对 empty 数组失败。
    猜你喜欢
    • 2016-08-20
    • 2017-02-21
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-21
    • 2021-08-25
    • 1970-01-01
    相关资源
    最近更新 更多