gpt4 book ai didi

arrays - Mongoose 模式需要可以为空的数组

转载 作者:行者123 更新时间:2023-12-04 01:56:35 25 4
gpt4 key购买 nike

我有这个架构

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

mongoose.model('Stuff', StuffSchema);

工作正常。

现在我需要添加另一个包含这个的模式“ cargo ”
mystuff: { type:[String], ref: 'Stuff', required:true},

也就是说,我希望 mystuff 包含 Stuff 的 id 数组,但是在运行此代码时会因验证错误而失败
mongoose.model('Cargo').create( some data...)

如果我对 mystuff 字段使用空数组。
如果我将 Cargo 架构更改为
mystuff: { type:[String], ref: 'Stuff'},

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

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

最佳答案

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

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

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

关于arrays - Mongoose 模式需要可以为空的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27268172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com