Currently, I am in the process of developing a shopping cart system. While I have successfully created one using MongoDB, I seem to be facing an issue when it comes to adding products from the database to the cart. Upon inspection in both the console.log and MongoDB GUI, only an empty items array is displayed. Any assistance on resolving this matter would be greatly appreciated.
const express = require('express');
const Carts = require('../repo/carts');
const router = express.Router();
router.post('/cart/products', async (req, res) => {
Carts.findById(req.session.cartId, (err, foundCart) => {
if(err) {
console.log(err)
}
if (foundCart) {
console.log(foundCart);
Carts.update( { _id:req.session.cartId }, {
$push: {
items: {
_id: req.body.productId,
quantity: 1,
},
},
});
} else {
if (!foundCart) {
const newCart = new Carts({
_id: req.session.cartId,
items: [],
});
newCart.save();
}
}
});
res.send('product added to cart!!');
});
module.exports = router;
Here's a glimpse at the carts schema for MongoDB:
const mongoose = require('mongoose');
const cartSchema = new mongoose.Schema({
_id: String,
items: [
{ quantity: Number, _id: String,}
]
});
const Carts = new mongoose.model('Carts', cartSchema);
module.exports = Carts;
See the image of how the cart appears in MongoDB Robo3T https://i.sstatic.net/mDBpC.png.