node.js - Can a Schema use it's own model to validate? -


for example, have user schema, , want validate username unique before attempting save user database.

...  userschema.path('username')   .validate(function (value, respond) {     user.findone({ username: this.username }) // isn't valid.       .lean()       .select('_id')       .exec(function (err, user) {          if (err) {           winston.warn('user_username: error looking duplicate users');           respond(false);         }          // if user returned, user non-unique!         if (user) {           respond(false);         }          respond(true);       });   });  ...  var user = mongoose.model('user', userschema); 

i know use mongoose.model('user').findone(...) seems bit silly, there no better way it?

you can create unique index in schema setting unique: true. make use of unique index option available in mongodb. here example snippet 1 of models using option:

// (generated) uniform resource locator url: {     // ... required ...     required: true,     // ... unique index ...     unique: true,     // ... , string.     type: string } 

compound key comments:

schema.index({ username: 1, accountcode: 1 }, { unique: true }) 

Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

css - Can I use the :after pseudo-element on an input field? -