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
I managed to solve this by using Promises as follows.
This catches the validation errors correctly.
when defining a schema, you can also define error message for better approach
the schema would be like:
when create is called without
name
or any field that isrequired
, it will thrown property err message inside propertiyerrors
:regarding to validation-errors documentation, to handle the error would be: