Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Mongoose Cannot Update Instead Create A New Array without wasting too much if your time.
The question is published on by Tutorial Guruji team.
The question is published on by Tutorial Guruji team.
I cannot update my collection even without encountering any error. Can someone help? Please I am troubleshooting this for like 3 hours now.
const product_id = req.body.cartItems.product_id; const item = cart.cartItems.find(c => c.product_id == product_id); if (item) { Cart.findOneAndUpdate({ "user": req.user._id, "cartItems.product_id" : product_id }, { "$set": { "cartItems.$":{ ...req.body.cartItems.quantity, quantity: item.quantity + req.body.cartItems.quantity } } }) .exec((error, _cart) => { if (error) return res.status(400).json({ error }); if (_cart) { return res.status(201).json({ _cart }); } });
The MODEL:
const mongoose = require('mongoose'); const cartSchema = new mongoose.Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true}, cartItems: [ { product_id: { type: mongoose.Schema.Types.ObjectId, ref: 'Product', required: true}, // This foreign key to product _id quantity: {type: Number,required: true}, price: {type: Number, required: true} } ] }, {timestamps: true}); module.exports = mongoose.model('Cart', cartSchema);
Answer
You need to use the $[] operator to update all documents inside the cartItems array matching your filter criteria. This operator acts like a placeholder for all items in the array. Considering your coding it would be something like this:
Cart.findOneAndUpdate({ "user": req.user._id, "cartItems.product_id" : product_id }, { "$set": { "cartItems.$[].quantity": item.quantity + req.body.cartItems.quantity } }).exec(...)
We are here to answer your question about Mongoose Cannot Update Instead Create A New Array - If you find the proper solution, please don't forgot to share this with your team members.