我试图做的经典的事情,确保用户的用户名是不一样的他们的密码,在Nodejs/Mongoose。
我想使用一个单独的验证函数会很好,但是我不知道怎么做。
到目前为止,我已经使用了Alex Young的记事本教程中的模型代码。他创建了一个虚拟的password
属性,我已经重用了。
我已经得到了如下的基本验证:
function validatePresenceOf(value) {
return value && value.length;
}
User = new Schema({
'username': {
type: String,
validate: [
validatePresenceOf, 'a username is required',
],
index: { unique: true }
},
});
我如何允许验证器访问其他属性?
您可以通过this. propertytobec被叫来调用模式的其他属性。
schema.path('name').validate(function(v) {
if (v === this.password) {
return false;
} else {
return true;
}
}, 'my error type');
或者类似的东西
使用Mongoose 5,我无法得到为我工作的公认答案。
相反,遵循这个答案中的预验证中间件方法,使用invalidate,这就达到了目的:
schema.pre('validate', function (next) {
if (this.username === this.password) {
this.invalidate('password', 'Password cannot equal username', this.password);
}
next();
});