[英]Is there a way to refer to the current model's _id field during validation in mongoose?
我有一個模式。 唯一的處方是唯一性驗證。
User.path("email").validate(hasUnique("email"), "uniqueness");
hasUnique
返回mongoose
將用來驗證值的唯一性的函數。
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
,但此驗證被調用並失敗,因為它在集合中看到自己的電子郵件,並認為這不是唯一的。
有沒有辦法可以將文檔本身排除在hasUnique
返回的驗證函數中? 我的想法是,我可以添加$ not謂詞以在查詢中排除當前文檔的_id字段。
在貓鼬驗證功能中, this
是正在驗證的文檔。
因此,您可以執行以下操作:
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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.