Mongoose getter / setters for normalizing data

前端 未结 1 1669
慢半拍i
慢半拍i 2021-02-09 12:49

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

相关标签:
1条回答
  • 2021-02-09 13:12

    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;
    });
    
    0 讨论(0)
提交回复
热议问题