Mongoose getter / seters to normalize data

I have a User scheme that has a username field. I would like this field to be case sensitive so that users can register names like BobDylan . However, I need my scheme to check for new entries to check for duplicates; incase is sensitive, like BobDylan .

My research taught me that I have to create an extra field in the schema to store the lowercase / uppercase version so that I can easily check if it is unique. My question is, how can I achieve this using the Mongoose API?

I tried using the set function, for example:

 UserSchema.path('username_lower_case').set(function(username_lower_case) { return this.username.toLowerCase() }); 

However, this feature does not seem to work. I basically need to tell username_lower_case to be username , but lowercase.

+6
source share
1 answer

One way is to use a preliminary glitch for this.

 UserSchema.pre('save', function (next) { this.username_lower_case = this.username && this.username.toLowerCase(); next(); }); 

Another way would be to make username virtual:

 UserSchema.virtual('username').set(function (value) { this.username_raw = value; this.username_lower_case = value && value.toLowerCase(); }).get(function () { return this.username_raw; }); 
+10
source

All Articles