【发布时间】:2015-11-05 08:37:38
【问题描述】:
有没有办法检查验证器中的路径是否已被修改?是否需要检查或仅在路径更改时才运行验证器?
编辑:
更具体地说,我试图在插入 id 之前确保作者存在:
var BookSchema = new Schema({
title: { type: String, required: true },
authorId: { type: Schema.Types.ObjectId, ref: 'Author' }
});
BookSchema.path('authorId').validate(function(authorId, done) {
Author.getAuthorById(authorId, function(err, author) {
if (err || !author) {
done(false);
} else {
done(true);
}
});
}, 'Invalid author, does not exist');
在这种情况下,我只想验证是否设置了 authorId 或是否更改。我是否需要检查函数中是否发生了更改,或者我是否可以假设仅当 authorId 更改并且不是 null/undefined 时才调用此验证器?
这让我看起来可以调用 isModified,但我不认为这是 'this' 上的一个函数。 Mongoose validation only when changed
【问题讨论】: