skip to Main Content

I am trying to create a post request to a MongoDB database. The schema has some required attributes and I am trying to handle ValidationErrors from requests that are missing these required attributes.


const post_property = async (req, res) => {
    try {
        const ppty = new Properties(req.body);

        ppty.save();
        res.status(201).json({status: true, msg: "Property created", property: ppty});
    } catch (error) {
        if (error instanceof mongoose.Error.ValidationError) {
            res.status(400).json({status: false, msg: error.message});
        }

        res.status(500).json({status: false, msg: error.message});
    }
}

My schema looks like this:

const PropertiesSchema = new mongoose.Schema(
    {
        name: { type: String, required: true },
        address: {
            street: { type: String, required: true },
            number_or_apt: { type: String, required: true },
            city: { type: String, required: true },
            state_province: { type: String, required: true },
            zip_code: { type: String, required: true },
            country: { type: String, required: true },
            latitude: { type: String, required: true },
            longitude: { type: String, required: true },
        },
        property_images: [ String ],
    }
);

const Properties = mongoose.model('properties', PropertiesSchema);

Whenever I send the request with a missing required component the node server crashes. How can I handle this error?

I have tried implementing middleware to handle the error but that did not work.

2

Answers


  1. Chosen as BEST ANSWER

    I managed to solve this by using Promises as follows.

    Properties.create(req.body)
      .then((ppty) => {
        ppty.save();
        res.status(201).json({status: true, msg: "Property created", property: ppty});
      })
      .catch((err) => {
        res.status(400).json({ status: false, msg: err });
    });
    

    This catches the validation errors correctly.


  2. when defining a schema, you can also define error message for better approach

    the schema would be like:

    name: { type: String, required: [true, 'Name is required.'],  },
    

    when create is called without name or any field that is required, it will thrown property err message inside propertiy errors:

    `"Event validation failed: name: Name is required."`
    

    regarding to validation-errors documentation, to handle the error would be:

    try {
      ...
    } catch (error) {
      const errMsg = error.message ? error.message : error.errors.message
      //  use statuscode 400, because the error is about bad request.
      res.status(400).json({ status: false, msg: errMsg });
    }```
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search