For example, say I have a user schema, and I want to validate that the username is unique before even attempting to save the user to the database.
...
UserSchema.path('username')
.validate(function (value, respond) {
User.findOne({ username: this.username }) // This isn't valid.
.lean()
.select('_id')
.exec(function (err, user) {
if (err) {
winston.warn('User_username: Error looking for duplicate users');
respond(false);
}
// If a user was returned, then the user is non-unique!
if (user) {
respond(false);
}
respond(true);
});
});
...
var User = mongoose.model('User', UserSchema);
I know I could use mongoose.model('User').findOne(...) but that just seems a bit silly, is there no better way to do it?
You can create an unique index in your schema by setting unique: true. This will make use of the unique index option that is available in mongodb. Here is an example snippet from one of my models using this option:
// The (generated) uniform resource locator
url: {
// ... which is required ...
required: true,
// ... which is an unique index ...
unique: true,
// ... and is a string.
type: String
}
Compound key from comments:
Schema.index({ username: 1, accountCode: 1 }, { unique: true })