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
Post a Comment