【问题标题】:Validating multiple Mongoose schema properties?验证多个猫鼬模式属性?
【发布时间】:2011-11-14 05:19:30
【问题描述】:

我正在尝试做经典的事情,即在 Nodejs/Mongoose 中确保用户的用户名与其密码不同。

我认为使用单独的验证功能会很好,但我不知道该怎么做。

到目前为止,我使用的是model code from Alex Young's Notepad tutorial。他创建了一个我重复使用的虚拟password 属性。

我有如下基本验证:

function validatePresenceOf(value) {
    return value && value.length;
}

User = new Schema({
    'username': {
        type: String,
        validate: [
            validatePresenceOf, 'a username is required',
        ],
        index: { unique: true }
    },
});

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

【问题讨论】:

    标签: validation node.js mongoose


    【解决方案1】:

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

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

    或者类似的东西。

    【讨论】:

      【解决方案2】:

      使用 Mongoose 5,我无法获得为我工作的公认答案。

      相反,遵循this answer 中的pre-validate middleware 方法,使用invalidate,这成功了:

      schema.pre('validate', function (next) {
        if (this.username === this.password) {
          this.invalidate('password', 'Password cannot equal username', this.password);
        }
        next();
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-02-23
        • 1970-01-01
        • 1970-01-01
        • 2021-12-18
        • 1970-01-01
        • 2021-06-20
        • 2022-01-12
        相关资源
        最近更新 更多