我一直在尝试运行自定义验证程序以检查用户输入的名称是否已存在于数据库中。因为,mongoDb将大写和小写名称视为不同,我为它创建了自己的验证器。在猫鼬更新查询中运行自定义验证
function uniqueFieldInsensitive (modelName, field){
return function(val, cb){
if(val && val.length){ // if string not empty/null
var query = mongoose.models[modelName]
.where(field, new RegExp('^'+val+'$', 'i')); // lookup the collection for somthing that looks like this field
if(!this.isNew){ // if update, make sure we are not colliding with itself
query = query.where('_id').ne(this._id)
}
query.count(function(err,n){
// false when validation fails
cb(n < 1)
})
} else { // raise error of unique if empty // may be confusing, but is rightful
cb(false)
}
}
}
现在的问题是,验证,同时节省在DB文件运行,但不能同时更新。
因为我使用猫鼬版本4.x,我也试过在我的更新查询中使用{ runValidators: true }
。这不起作用,因为我的验证器中的'this'关键字是'null',而在更新的情况下,它指的是在保存的情况下更新的文档。
能否让我知道是否有一些我错过了或有任何其他方式,我可以在更新查询中运行自定义验证器。