We are going to add a “Remove” button so the user can remove a product from the cart. Open the main.js
file in the routes
folder and type in the following code. The cart.ejs
file will be shown at the end of the article.
router.post('/remove', function(req, res, next) {
Cart.findOne({ owner: req.user._id }, function(err, foundCart) {
foundCart.items.pull(String(req.body.item));
foundCart.total = (foundCart.total - parseFloat(req.body.price)).toFixed(2);
foundCart.save(function(err, found) {
if (err) return next(err);
req.flash('remove', 'Successfully removed');
res.redirect('/cart');
});
});
});