模式验证中所需的 Mongoose 数组不起作用

Mar*_*690 4 mongoose mongodb mongoose-schema

在我的架构中,我需要有一个属性,它是一个必须始终不为空且不为未定义的数组。

所以我定义了它是必需的,但是验证并没有像我预期的那样工作,因为如果我省略了这个属性,就不会抛出任何错误。

在简单属性(不是数组)的情况下,这按我的预期工作

const nodeSchema = new Schema({
    address: { type: String, required: true },
    outputs: { type: [String], required: true }
})
Run Code Online (Sandbox Code Playgroud)

ILo*_*ius 5

我认为您可以通过添加这样的自定义验证器来修复它:

const nodeSchema = new Schema({
    address: { type: String, required: true },
    outputs: {
      type: [String],
      required: true,
      validate: [(value) => value.length > 0, 'No outputs'],
    }
})
Run Code Online (Sandbox Code Playgroud)

我希望它能帮助你。


Mar*_*690 0

数组隐式具有默认值 [](空数组)。

这就是问题所在

  • 老实说,我不确定修复是什么?您可以在答案中分享一些代码吗? (3认同)