我正在使用猫鼬。因此,在我的一个模式中,我只想在特定字段满足条件时才设置必填字段为true。所以我写了一个函数来设置必填字段只有在条件为真时才为真。但即使条件错误,所需的标志也是正确的。甚至函数内的控制台也没有被执行。我究竟做错了什么?提前致谢
这是我的架构
var ApplicationsSchema = new Schema({
first_name: {
type: String,
required: function(value) {
console.log('inside function')
console.log(this.status)
return this.status === 'submit';
},
validate: [validateLocalStrategyProperty, 'Please fill in the name of the Organization']
},
last_name: {
type: String,
validate: [validateLocalStrategyProperty, 'Please fill in the name of the Organization']
},
phone_number: {
type: String,
validate: [validateLocalStrategyProperty, 'Please fill in the phone number']
},
status:{
type: String,
}
});
mongoose.model('Applications', ApplicationsSchema);
答案 0 :(得分:1)
也许您可以添加自定义验证,而不是像这样的验证必填字段,只有在您选择的字段被选中时才会有效。在这种情况下,您的模型看起来像
var ApplicationsSchema = new Schema({
first_name: {
type: String,
validate: [validateLocalStrategyProperty, 'Please fill in the name of the Organization']
},
last_name: {
type: String,
validate: [validateLocalStrategyProperty, 'Please fill in the name of the Organization']
},
phone_number: {
type: String,
validate: [validateLocalStrategyProperty, 'Please fill in the phone number']
},
status:{
type: String,
}
});
ApplicationSchema.pre('validate', function(next){
let _this = this;
if(_this.status === 'submit' && !_this.first_name) { //status is submit and first name is not present -> error
_this.invalidate("first_name", "First name is required");
return next("first_name");
} else { // no error
next()
}
});
mongoose.model('Applications', ApplicationsSchema);