0

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);
});

2 Answers 2

2

The save method is asynchronous and returns a promise. In your case, newProduct.save() returns a promise which is not being fulfilled and no error is actually thrown:

app.post('/products', async (req, res, next) => {
    try {
        const newProduct = new Product(req.body);
        await newProduct.save();
        res.redirect(`/products/${newProduct._id}`);
    }
    catch (e) {
        next(e);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

The best solution would be validate req.body with a validator and save newProduct after it is validated. It'd be better to return the newProduct after it is saved rather than redirecting to certain endpoint.

If it is not validated you can throw your custom error.

I recommend using JOI which is very easy to use.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.