首页 > 解决方案 > 基于所需的 Mongoose 子文档验证

问题描述

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.jsmongoose

解决方案


要使除公寓以外的所有字段都需要,您只需使用 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 文档的此页面,以查看内置验证器是否足以满足您的目的,或者您是否需要在某些字段上使用自定义验证器。


推荐阅读