【问题标题】:mongoose getting Model validation failed instead of custom error message猫鼬获取模型验证失败而不是自定义错误消息
【发布时间】:2015-09-05 20:14:46
【问题描述】:

我确定问题出在密码验证器上,因为如果我将其注释掉,文档就会被插入。此外,如果我输入有效密码,一切正常。这是我的整个 UserSchema

var UserSchema = new Schema({
    firstName: String,
    lastName: String,
    email: {
        type: String,
        unique: true,
        match: /.+\@.+\..+/
    },
    website: {
        type: String,
        set: urlModifier
    },
    username: {
        type: String,
        trim: true,
        required: true,
        unique: true
    },
    password: {
        type: String,
        validate: [
          function(password) {
            return password.length >= 6;
          },
        'Password should be longer'
    ]
    },
    createdAt: {
        type: Date,
        default: Date.now
    },
    role: {
        type: String,
        enum: ['admin', 'owner', 'user']
    }
});

我遇到的这个问题是我得到的不是自定义错误消息

ValidationError: User validation failed
<br> &nbsp; &nbsp;at model.Document.invalidate (C:\Users\lotus\Desktop\mastering_mean\application\node_modules\mongoose\lib\document.js:1162:32)
    <br> &nbsp; &nbsp;at C:\Users\lotus\Desktop\mastering_mean\application\node_modules\mongoose\lib\document.js:1037:16
        <br> &nbsp; &nbsp;at validate (C:\Users\lotus\Desktop\mastering_mean\application\node_modules\mongoose\lib\schematype.js:651:7)
            <br> &nbsp; &nbsp;at C:\Users\lotus\Desktop\mastering_mean\application\node_modules\mongoose\lib\schematype.js:679:9
                <br> &nbsp; &nbsp;at Array.forEach (native)
                    <br> &nbsp; &nbsp;at SchemaString.SchemaType.doValidate (C:\Users\lotus\Desktop\mastering_mean\application\node_modules\mongoose\lib\schematype.js:656:19)
                        <br> &nbsp; &nbsp;at C:\Users\lotus\Desktop\mastering_mean\application\node_modules\mongoose\lib\document.js:1035:9
                            <br> &nbsp; &nbsp;at process._tickCallback (node.js:355:11)

Mongoose 版本是 ^4.05

不确定这是错误、API 中的某些更改,还是我做错了什么。

【问题讨论】:

    标签: mongoose


    【解决方案1】:

    在我正在学习的特定教程中没有提到这一点。

    http://mongoosejs.com/docs/validation.html

    自定义错误消息在作为 err 返回到控制器中的 save(err) 函数的验证错误对象中可用。

    基本

    user.save(函数(错误){ 如果(错误){ 返回下一个(错误); } 别的 { res.json(用户); } });

    将返回默认错误消息“用户验证失败”

    这个

    user.save(function(err) {
            if(err) {
                console.log(err.errors.password.message);
                return next(err);
            } else {
                res.json(user);
            }
        });
    

    将返回自定义错误信息

    【讨论】:

      猜你喜欢
      • 2016-03-13
      • 2021-02-24
      • 1970-01-01
      • 1970-01-01
      • 2016-02-14
      • 2018-11-17
      • 1970-01-01
      • 2010-12-14
      • 1970-01-01
      相关资源
      最近更新 更多