Tuesday, 6 June 2017

How to pass only Error messages from Model to Controller (Mongoose)?

I'm building my node.js api and want to pass on the callback only messages about errors. Now I need to have a deal with object like this

{
    "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"
    }
}

Here is my code 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}.`});
        });
    };

Of course I can make a function on the frontend that search for 'message' keys but for some records it could be more than 100 errors. Is it anyway how I can do it and do not pass the redundancy data?



via user3315525

No comments:

Post a Comment