验证多个Mongoose架构属性?

Ben*_*eys 6 validation mongoose node.js

我想尝试在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 }
    },
});
Run Code Online (Sandbox Code Playgroud)

我如何允许验证器访问其他属性?

小智 8

您可以通过this.propertyToBeCalled调用架构的其他属性.

schema.path('name').validate(function(v) {
    if (v === this.password) {
        return false;
    } else {
        return true;
    }
}, 'my error type');
Run Code Online (Sandbox Code Playgroud)

或者类似的东西.