我是 Mongoose 的新手,想知道是否可以根据查询动态添加某些参数的验证器。例如,我有一个如下所示的架构:
var user = new Schema({
name: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
city: { type: String },
country: { type: String }
});
为了进行简单的注册,我强制用户提供姓名、电子邮件和密码。上面的架构没问题。现在稍后我想强制用户给予城市和国家。 例如,是否可以根据需要使用参数城市和国家/地区更新用户的文档?我避免重复用户架构,如下所示:
var userUpdate = new Schema({
name: { type: String },
email: { type: String },
password: { type: String },
city: { type: String, required: true },
country: { type: String, required: true }
});
最佳答案
在这种情况下,您需要做的是拥有一个架构,并使您的required
成为一个允许null
和String
的函数:
var user = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
city: {
type: String,
required: function() {
return typeof this.city === 'undefined' || (this.city != null && typeof this.city != 'string')
}
}
});
您可以提取它并使其成为一个外部函数,然后您可以将其用于county
等。
它的作用是使该字段成为必填字段,但您也可以为其设置 null
。通过这种方式,您可以在开始时将其设置为空,然后再将其设置。
Here is the doc 必需
。
关于node.js - Mongoose:根据查询动态添加某些参数的验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51863847/