1

I am willing to update an exisiting shopping cart by using req.params.cart_id to find it and update the object inside the array, if product doesn't exist push a new product

This is my mongoose Schema

const shoppingCartSchema = mongoose.Schema({
    user_id: { type: String, required: true},
    cart_date: { type: String, required: true},
    activeCart: { type: Boolean, required: true },
    cart_content: [{
        product_id: { type: String, required: true},
        product_quantity: { type: Number, required: true},
    }]
})

Lets say I have a shopping cart :

{
    "_id" : ObjectId("5c6830c9a7e056443ce8befe"),
    "user_id" : "5c4e1a3cbc446733801b5a54",
    "cart_date" : "2019-02-16T15:48:25.464Z",
    "activeCart" : true,
    "cart_content" : [ 
        {
            "_id" : ObjectId("5c6830c9a7e056443ce8beff"),
            "product_id" : "1",
            "product_quantity" : 1
        }
    ],
    "__v" : 0
}

Method:

router.post("/:update", (req, res, next) => { 
     const cart_id = req.params['update'];
     const product_id = req.body.product_id;
     Cart.update({"_id": cart_id},
     //{Here to find the cart_content[index].product_id}
     //{add +1 to product_quantity if product_id === to the req.product_id}
     //{if no such product_id, push the new product {
      "product_id": req.body.product_id,
      "product_quantity": req.body.product_quantity
}).then(response => {
console.log(response);
} 
});

If updated result should be:

{
    "_id" : ObjectId("5c6830c9a7e056443ce8befe"),
    "user_id" : "5c4e1a3cbc446733801b5a54",
    "cart_date" : "2019-02-16T15:48:25.464Z",
    "activeCart" : true,
    "cart_content" : [ 
        {
            "_id" : ObjectId("5c6830c9a7e056443ce8beff"),
            "product_id" : "1",
            "product_quantity" : 2 ****
        }
    ],
    "__v" : 0
}

If no such id push new product:

{
    "_id" : ObjectId("5c6830c9a7e056443ce8befe"),
    "user_id" : "5c4e1a3cbc446733801b5a54",
    "cart_date" : "2019-02-16T15:48:25.464Z",
    "activeCart" : true,
    "cart_content" : [ 
        {
            "_id" : ObjectId("5c6830c9a7e056443ce8beff"),
            "product_id" : "1",
            "product_quantity" : 1
        }, {
            "_id" : ObjectId("5c6830c9a7e056443ce8b421"),
            "product_id" : "2",
            "product_quantity" : 1

    ],
    "__v" : 0
}
zhulien
  • 5,145
  • 3
  • 22
  • 36
Darmon
  • 303
  • 4
  • 17
  • I think you should check this one https://stackoverflow.com/questions/41316056/mongodb-update-array-element-document-with-a-key-if-exists-else-push it is describing the solution for same problem but not very efficient – mzparacha Feb 16 '19 at 16:37
  • @mzparacha There is no way to do this query in a single method? Thanks for the guide btw, will try it shortly – Darmon Feb 16 '19 at 17:37

0 Answers0