Mongoose getter / setter用于标准化数据
我有User
模式有一个username
段。 我希望这个字段区分大小写,以便用户可以注册BobDylan
等BobDylan
。 但是,我需要我的模式来validation新的条目,以检查没有重复,比如bobdylan
敏感。
我的研究告诉我,我应该在模式中创build一个额外的字段来存储一个小写/大写的版本,这样我可以很容易地检查它是否是唯一的。 我的问题是,我将如何实现这个与Mongoose API?
我曾尝试使用set
function,如:
UserSchema.path('username_lower_case').set(function(username_lower_case) { return this.username.toLowerCase() });
但是,这个function似乎并没有运行。 我基本上需要告诉username_lower_case
是什么username
,但小写。
一种方法是使用预保存钩子来做到这一点。
UserSchema.pre('save', function (next) { this.username_lower_case = this.username && this.username.toLowerCase(); next(); });
另一种方法是使用username
是虚拟的:
UserSchema.virtual('username').set(function (value) { this.username_raw = value; this.username_lower_case = value && value.toLowerCase(); }).get(function () { return this.username_raw; });