简体   繁体   中英

NodeJS,Mongoose: Required field validation

I can add a new item to the database if I get a correctly formatted JSON file in the body where every required field contains something. If its false, right now I just return a JSON file like this:

{
    "succes": false
}

But I also want to return an error message. I have already implemented the error string in the Model but I dont know how can I pull this out, if the catch block catches the error...

My add new item method:

exports.addBootcamp = async (req, res, next) => {
    try {
        const bootcamp = await Bootcamp.create(req.body);

        if (!bootcamp) {
            return res.status(404).json({ succes: false });
        }

        res.status(201).json({
            succes: true,
            data: bootcamp
        });
    } catch (err) {
        return res.status(404).json({ succes: false });
    }
};

The beggining part of my Model:

const BootcampShema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, 'Please add a name'], //first error message
        unique: true,
        trim: true,
        maxlength: [50, 'Name cannot be more than 50 characters']
    },
    slug: String,
    description: {
        type: String,
        required: [true, 'Please add a description'], //second error message
        maxlength: [500, 'Description cannot be more than 500 characters']
    },
    //...etc

Of course these are in seperate js files but I can export them.

In this case we'll get a ValidationError from database which will be encapsulated in error object. Modify your catch statement to below:

try {
// as it is
}
catch (err) {
        return res.status(404).json({
                                      succes: false,
                                      message: err.message
                                    });
}

Mongo db return the error object as below. From this structure you can extract whatever info you want and return that to user.

{
    "errors": {
        "name": {
            "message": "Please add a name",
            "name": "ValidatorError",
            "properties": {
                "message": "Please add a name",
                "type": "required",
                "path": "name"
            },
            "kind": "required",
            "path": "name"
        }
    },
    "_message": "Name validation failed",
    "message": "Name validation failed: camera_name: Please add a name",
    "name": "ValidationError"
}

Here Please add a name is the same text we entered in our model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM