我需要检查必填字段,但有些情况。我正在尝试以下方法:
var PostSchema = mongoose.Schema({});
PostSchema.pre('validate', function (next) {
var error = new ValidationError(this);
if (this.type === 'question' && !Array.isArray(this.tags)) {
error.errors.tags = new ValidatorError({message: 'Tags field is required', type: 'required', path: 'tags'});
}
if (!Object.keys(error.errors).length) {
return next();
} else {
return next(error);
}
});
将验证作为上述方法是否正确并且未来它不会破坏猫鼬?
答案 0 :(得分:1)
每mongoose doc,Validation
是middleware
的内部部分。我认为像你一样进行验证是正确的,我也用以下代码进行测试
var PostSchema = mongoose.Schema({
type: String,
tags: String,
});
PostSchema.pre('validate', function (next) {
var error = new ValidationError(this);
if (this.type === 'question' && !Array.isArray(this.tags)) {
error.errors.tags = new ValidationError({message: 'Tags field is required', type: 'required', path: 'tags'});
}
if (!Object.keys(error.errors).length) {
return next();
} else {
return next(error);
}
});
var Post = mongoose.model('Post', PostSchema);
var p = new Post({
type: 'question',
tags: 'abc'
});
p.save(function(err) {
if (err)
console.log(err);
else
console.log('save post successfully');
});
由于tags
不是Array
,它会触发validate
,错误显示如下
{ [ValidationError: Post validation failed]
message: 'Post validation failed',
name: 'ValidationError',
errors:
{ tags:
{ [ValidationError: Validation failed]
message: 'Validation failed',
name: 'ValidationError',
errors: {} } } }
由于Validation
是一个内部中间件,因此可以将其添加到代码中,并且只有在Validation
中间件未从mongoose中删除时才会破坏猫鼬。
顺便说一句,在这篇文章Handling Mongoose validation errors – where and how?中,this answer在此处也提供了相同的代码。