问题
I have a schema. And the only prescription, is a uniqueness validation.
User.path("email").validate(hasUnique("email"), "uniqueness");
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);
}
}
}
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.
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.
回答1:
In a Mongoose validation function, this
is the document being validated.
So you could do:
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);
}
}
}
来源:https://stackoverflow.com/questions/17507522/is-there-a-way-to-refer-to-the-current-models-id-field-during-validation-in-mo