node.js - 基于所需的 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)
解决方案
要使除公寓以外的所有字段都需要,您只需使用 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 文档的此页面,以查看内置验证器是否足以满足您的目的,或者您是否需要在某些字段上使用自定义验证器。
推荐阅读
- haskell - 如何在函数组合中打印中间结果
- hash - 如何在 Racket 中散列字符串?
- android - 可以创建组件但在 android 3.6.1 中无法获取引用
- python - 纸浆在选项/类型不能相同的地方添加新约束?
- vue.js - Vue2-Dropzone:如何使用 removeFile(file)?
- spring-cloud - 为什么负载均衡器无法使用 eureka 找到所需的微服务?
- regex - 来自文件的 Bash IP
- html - 如何在 vscode 中减小编辑器文件的宽度,以便不必向右滚动即可到达段落末尾
- c++ - 如何使用 tlhelp32 和 NtQuerySystemInformation
- r - 使用 grepl() 函数在 R 中进行模式匹配