I have User schema which has a username field. I would like this field to be case sensitive, so that users may register names such as BobDylan. However, I need my schema to validate new entries to check there are no duplicates, incase sensitive, such as bobdylan.
My research has taught me that I should create an additional field in the schema for storing a lower case / upper case version, so that I can easily check if it is unique. My question is, how would I achieve this with the Mongoose API?
I have tried using a set function, such as:
UserSchema.path('username_lower_case')
.set(function (username_lower_case) {
return this.username.toLowerCase()
})
However, this function doesn't seem to be running. I basically need to tell username_lower_case to be whatever username is, but in lower case.
One way would be to use a pre-save hook to do it.
UserSchema.pre('save', function (next) {
this.username_lower_case = this.username && this.username.toLowerCase();
next();
});
Another way would be to make username a virtual:
UserSchema.virtual('username').set(function (value) {
this.username_raw = value;
this.username_lower_case = value && value.toLowerCase();
}).get(function () {
return this.username_raw;
});