I have a userSchema like so:
var userSchema = new Schema({
name: {
type: String
, required: true
, validate: [validators.notEmpty, 'Name is empty']
}
, username: {
type: String
, required: true
, unique: true
, validate: [validators.notEmpty, 'Username is empty']
}
});
The username field is supposed to be unique. Mongoose will throw an error if this username already exists in the database. However, it is not case insensitive, which I need it to be.
Am I right in thinking that the only way to achieve a case insensitive unique check is to write my own validation rule, which will perform a query on the collection? Is it OK to write validation checks like this, creating more connections to the collection? I will need to do something similar for email, too.
What about using:
{ type: String, lowercase: true, trim: true }
to achieve your purpose?
How about using a regular expression?
var pattern = [ /some pattern/, "{VALUE} is not a valid user name!" ];
{ type: String, match: pattern }
For further reference: http://mongoosejs.com/docs/api.html#schematype_SchemaType-required