【问题标题】:Mongoose subdocument validation based on required基于所需的 Mongoose 子文档验证
【发布时间】:2018-10-31 06:25:24
【问题描述】:

TL;DR:如何使自定义类型字段在一种情况下需要(并对子文档运行验证)而在另一种情况下不需要(对子文档没有验证)?

我有一个adress 架构和使用此架构的模型(代码如下)。 在一种情况下它是必需的,而在另一种情况下则不是。那么如何正确验证address?如果此字段是必需的,则除了“公寓”之外的所有字段都应该是必需的,如果不需要,则可以为空或有效(对于索引情况)。

对于这种情况,是否有一些选项可以将一些选项传递给子架构,或者我应该在每个模型中制作自定义验证器?

// adress SCHEMA
module.exports = mongoose.Schema({
  town: String,
  index: {
    type: String,
    validate: {
      validator: function (v) {
        return /^\d+$/.test(v)
      },
      message: 'Invalid index'
    }
  },
  district: String,
  street: String,
  house: String,
  apartment: String
})

// user.js
const Address = require('./address')
const mongoose = require('mongoose')

const userSchema = mongoose.Schema({
  address: {
    type: Address,
    required: true // Adress required here
  }
})

module.exports = mongoose.model('User', userSchema)

// other.js
const Address = require('./address')
const mongoose = require('mongoose')

const otherSchema = mongoose.Schema({
  address: Address // but not here
})

module.exports = mongoose.model('Other', otherSchema)

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    要使除公寓以外的所有字段都需要,您只需使用 required 属性,就像使用地址一样:

    town: {type: String, required: true},
    district: {type: String, required: true},
    street: {type: String, required: true},
    house: {type: String, required: true},
    apartment: String
    

    如果其中一个必填字段为空,在使用 create 方法时会出现错误,可以处理该错误以将用户返回/保留在表单页面上并显示错误消息以通知他们需要填写必填字段

    至于验证,您可以查看官方 mongoose 文档的 this page 以查看内置验证器是否足以满足您的目的,或者您是否确实需要在某些字段上使用自定义验证器。

    【讨论】:

    • 我知道如何填写必填字段。我问过在不需要adress: {type: Adress} 的第二种情况下如何使它不需要?在这种情况下,它仍然会根据子架构所需的规则抛出错误。
    • @Iworb 不设置`地址:{类型:地址,要求:假}`工作?
    猜你喜欢
    • 2015-09-30
    • 2019-06-03
    • 2014-09-15
    • 2014-08-27
    • 1970-01-01
    • 2017-10-01
    • 2018-04-15
    • 1970-01-01
    • 2020-05-22
    相关资源
    最近更新 更多