Is there a way to refer to the current model's _id field during validation in mongoose?

拟墨画扇 提交于 2019-12-11 19:27:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!