Mongoose getter / setters for normalizing data

巧了我就是萌 提交于 2020-01-01 03:33:10

问题


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.


回答1:


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;
});


来源:https://stackoverflow.com/questions/14023937/mongoose-getter-setters-for-normalizing-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!