【问题标题】:Mongoose array required in schema validation not working架构验证所需的 Mongoose 数组不起作用
【发布时间】:2018-10-13 14:44:42
【问题描述】:

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

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

如果是简单属性(不是数组),这将按我的预期工作

const nodeSchema = new Schema({
    address: { type: String, required: true },
    outputs: { type: [String], required: true }
})

【问题讨论】:

    标签: mongodb mongoose mongoose-schema


    【解决方案1】:

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

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

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      数组隐含的默认值为 [](空数组)。

      这就是问题

      【讨论】:

      • 老实说,我不确定解决方法是什么?你能在你的答案中分享一些代码吗?
      猜你喜欢
      • 2019-02-13
      • 2018-09-07
      • 2018-05-25
      • 1970-01-01
      • 1970-01-01
      • 2012-09-11
      • 2016-09-11
      • 2017-02-01
      • 1970-01-01
      相关资源
      最近更新 更多