Here is the POST request for /products. When a form is submitted, this function will be triggered, utilizing try-catch to handle any errors that may occur if the form is submitted incorrectly.
This is the Schema being used:
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']
}
});
If there is an issue with the newProduct.save() line, such as submitting a form that violates the Schema by not including a name, an error will be generated instead of redirecting 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);
}
});
Below is my error handling middleware:
app.use((err, req, res, next) => {
const { status = 500, message = 'Something went wrong!' } = err;
res.status(status).send(message);
});