如何仅将模型中的错误消息传递给控制器​​(Mongoose)?

时间:2017-06-06 20:58:12

标签: javascript node.js mongodb mongoose

我正在构建我的node.js api,并希望仅传递有关错误的回调消息。现在我需要处理像这样的对象

{
    "success": false,
    "msg": {
        "errors": {
            "email": {
                "message": "test@tes is not a valid email!",
                "name": "ValidatorError",
                "properties": {
                    "type": "user defined",
                    "message": "{VALUE} is not a valid email!",
                    "path": "email",
                    "value": "test@tes"
                },
                "kind": "user defined",
                "path": "email",
                "value": "test@tes"
            },
            "username": {
                "message": "The Username is not long enough",
                "name": "ValidatorError",
                "properties": {
                    "type": "user defined",
                    "message": "The Username is not long enough",
                    "path": "username",
                    "value": "te"
                },
                "kind": "user defined",
                "path": "username",
                "value": "te"
            }
        },
        "_message": "Users validation failed",
        "name": "ValidationError"
    }
}

这是我的代码 的 userModel.js

/* Custom Validation */
const validator = (v)=> {
    return v.length > 5;
};
/* END of Custom Validation */

const UserSchema = new Schema({
        username: {
            type: String,
            validate: [
                validator,
                'The Username is not long enough'
            ],
            required: [true, 'The Username is required'],
            unique: true,
            lowercase: true
        },
        password: {
            type: String,
            required: [true, 'The Password is required']
        },
        email: {
            type: String,
            validate: [
                (v)=> { return /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i.test(v)},
                '{VALUE} is not a valid email!'
            ],
            lowercase: true,
            required: true
        },
        role: {
            type: [{
                type: String,
                enum: ['user', 'manager', 'admin']
            }],
            default: ['user']
        },
        team: {
            type: [{
                type: String,
                enum: ['IHLO', 'ADULT&SH', 'IPJ', 'ISD', '']
            }],
            default: ['']
        },
        created_date: {
            type: Date,
            default: Date.now
        },

    });

    UserSchema.pre('save', ...

    UserSchema.methods.comparePassword = ...

    module.exports = mongoose.model('Users', UserSchema);
**userController.js**

    / Register new user
    exports.signup = (req, res)=> {

        let new_user = new User(req.body);
        new_user.save((err, new_user)=> {
            if (err)
                return res.json({success: false, msg: err});
            res.json({success: true, msg: `Successful created new user ${new_user.username}.`});
        });
    };

当然,我可以在前端搜索&#39; message&#39;密钥,但对于某些记录,它可能超过100个错误。无论如何我是如何做到的并且不传递冗余数据?

2 个答案:

答案 0 :(得分:1)

您可以在将错误对象发送到前端之前简单地解析错误对象。

以下是如何使用循环执行此操作的方法。

if (err){
    let messages = [];
    for(let i in err){
        messages.push({
            field: i,
            message: err[i].message
        });
    }

    return res.json({success: false, msg: messages});
}

您还可以使用像lodash这样的库来使它更清洁。

if (err){
    let messages = _.flatMap(err, (value, key) => { field: key, message: value.message });
    return res.json({success: false, msg: messages});
}

答案 1 :(得分:0)

突起

User.find({}, {messages: 1})

User.find({},'messages')

第二个参数是投影mongoose api

我认为你也可以User.find({},'messages -_id')省略_id但是如果你正在使用对象你可以做{_id : 0}

如果要过滤掉包含错误消息的对象:

您可以使用.lean()制作真正的js对象

做类似

的事情
User.find({}).lean()
.then(users =>{
  user.filter(e => e.name == "ValidationError")
})

Haven未经过测试