问题描述
我有一个模式.唯一的处方是唯一性验证.
I have a schema. And the only prescription, is a uniqueness validation.
User.path("email").validate(hasUnique("email"), "uniqueness");
hasUnique
返回mongoose
将用于验证值唯一性的函数.
hasUnique
returns the function that will be used by mongoose
to validate the uniqueness of the value.
function hasUnique(key) {
return function(value, respond) {
var query = {};
query[key] = /A regex used to look up the email/;
User.findOne(query, function(err, user) {
respond(!user);
}
}
}
这在创建新文档时效果很好.但是,当我查询文档,更改属性然后调用save
时,此验证将被调用并失败,因为它在集合中看到了自己的电子邮件,并认为这不是唯一的.
This works well when a new document is created. But when I query a document, mutate an attribute then call save
, this validation gets called and fails because it sees its own email in the collection and thinks this isn't unique.
是否可以在hasUnique
返回的验证函数中排除文档本身?我的想法是,我可以添加$ not谓词以在查询中排除当前文档的_id字段.
Is there a way I can exclude the document itself in the validation function returned from hasUnique
? My thought is that I can add a $not predicate to exclude the current doc's _id field in the query.
推荐答案
在Mongoose验证功能中,this
是要验证的文档.
In a Mongoose validation function, this
is the document being validated.
所以您可以这样做:
function hasUnique(key) {
return function(value, respond) {
var query = { _id: { $ne: this._id }};
query[key] = /A regex used to look up the email/;
User.findOne(query, function(err, user) {
respond(!user);
}
}
}
这篇关于在猫鼬验证期间,有没有办法引用当前模型的_id字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!