用于规范化数据的Mongoose getter / setters [英] Mongoose getter / setters for normalizing data
问题描述
我有用户
模式,它有一个用户名
字段。我想这个字段是区分大小写的,所以用户可以注册一些名字,例如 BobDylan
。但是,我需要我的模式来验证新条目,以检查没有重复项,不敏感,例如 bobdylan
。
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
.
我的研究告诉我,我应该在架构中创建一个额外的字段,用于存储小写/大写版本,以便我可以轻松地检查它是否是唯一的。我的问题是,如何使用Mongoose API实现这一点?
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()
});
但是,这个函数似乎没有运行。我基本上需要告诉 username_lower_case
,而不是用户名
是,但小写。
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();
});
另一种方法是使 username
a虚拟:
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;
});
这篇关于用于规范化数据的Mongoose getter / setters的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!