So this is the POST request for /products, when a form is submitted, this function will be invoked. I use a try-catch to catch the error if the form is submitted wrongly.
This is my Schema.
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
price: {
type: Number,
required: true,
min: 0
},
category: {
type: String,
lowercase: true,
enum: ['fruit', 'vegetable', 'dairy']
}
});
The error is with the newProduct.save() line, so if I submit a form that goes against the Schema, like not having a name, I will get an error instead of getting redirected to the page.
app.post('/products', (req, res, next) => {
try {
const newProduct = new Product(req.body);
newProduct.save();
res.redirect(`/products/${newProduct._id}`);
}
catch (e) {
next(e);
}
});
This is my error handler.
app.use((err, req, res, next) => {
const { status = 500, message = 'Something went wrong!' } = err;
res.status(status).send(message);
});