-
-
Save calvin-puram/036e9978925224162d51d4c8d90dfa6a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
router.post('/product/:product_id', passportConf.isAuthenticated, (req, res, next) => { | |
Cart.findOne({owner: req.user._id}, (err, cart) => { | |
cart.items.push({ | |
item: req.body.product_id, | |
price: parseFloat(req.body.priceValue), | |
quantity: parseInt(req.body.quantity) | |
}); | |
cart.total = (cart.total + parseFloat(req.body.priceValue)).toFixed(2); | |
cart.save((err) => { | |
if (err) return next(err); | |
return res.redirect('/cart'); | |
}) | |
}); | |
}); | |
router.get('/cart', passportConf.isAuthenticated, (req, res, next) => { | |
Cart.findOne({owner: req.user._id}) | |
.populate('items.item') | |
.exec((err, foundCart) => { | |
if (err) return next(err); | |
res.render('main/cart', { | |
foundCart: foundCart, | |
message: req.flash('remove') | |
}); | |
}); | |
}); | |
router.post('/remove', passportConf.isAuthenticated, (req, res, next) => { | |
Cart.findOne({owner: req.user._id}, (err, foundCart) => { | |
foundCart.items.pull(String(req.body.item)); | |
foundCart.total = (foundCart.total - parseFloat(req.body.price)).toFixed(2); | |
foundCart.save((err, found) => { | |
if (err) return next(err); | |
req.flash('remove', 'Successfully removed the product'); | |
res.redirect('/cart'); | |
}); | |
}); | |
}); | |
const mongoose = require('mongoose'); | |
const Schema = mongoose.Schema; | |
const CartSchema = new Schema({ | |
owner: {type: Schema.Types.ObjectId, ref: 'User'}, | |
total: {type: Number, default: 0}, | |
items: [{ | |
item: {type: Schema.Types.ObjectId, ref: 'Product'}, | |
quantity: {type: Number, default: 1}, | |
price: {type: Number, default: 0} | |
}] | |
}); | |
module.exports = mongoose.model('Cart', CartSchema); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment