Home > database >  How to iterate through nested document passed as a json body, and update every document in a collect
How to iterate through nested document passed as a json body, and update every document in a collect

Time:06-01

I am trying to update multiple documents in a collection for an ecommerce workshop for school and I don't know how to update the documents that needs their quantity changed according to how much the client has bought

this is how the json body is being received from frontend:

{
    "clientId": "123123",
    "cartItems": [
        { 
            "itemId":"6547",
            "quantity":"3" 
        }, {
            "itemId": "6543", 
            "quantity": "2"
        }
    ], 
    "address": "123 main street",
    
    "creditCardNumber":"1234567890123456"
}

I would like to iterate through the cartItems array and update the my Items collection in my database

Each document in my collection looks something like this:

{
    "_id":"6543",
    "name":"Barska GB12166 Fitness Watch with Heart Rate Monitor",
    "price":"$49.99",
    "body_location":"Wrist",
    "category":"Fitness",
    "imageSrc":"data:image/jpeg;base64...",
    "numInStock":"9",
    "companyId":"19962"
}

CodePudding user response:

This piece of code will work for you as a reference.


async function updateQuantity(itemId,quantityOfOrderedItem){

    const docs = await ItemModel.findById(itemId);
        const quantity = docs.quantity;
        const avialableQuant = docs.Available_quantity;
     
         const new_quantity = parseInt(avialableQuant - quantityOfOrderedItem);
        
        const item =  await ItemModel.findByIdAndUpdate(itemId,
            { $set: { "Available_quantity": new_quantity}},
            {
                new: true, 
                runValidators : true
            });
}
        const docs = await Model.findById(cartID);
        const itemarray = [];
        const items = docs.items;
        var arrayLength = items.length;
        for (var i = 0; i < arrayLength; i  ) {
            itemarray.push(items[i]);
        }
        for (var i = 0; i < itemarray.length; i  ) { 
            updateQuantity(itemarray[i].itemId,itemarray[i].quantity); 
        }

CodePudding user response:

order.cartItems.forEach(async (item) => {
      const result = await db
        .collection("items")
        .updateOne(
          { _id: parseInt(item.itemId) },
          { $inc: { numInStock: -parseInt(item.quantity) } }
        );
    });

then to restore the numInStock

result.cartItems.forEach(async (item) => {
      const result = await db
        .collection("items")
        .updateOne(
          { _id: parseInt(item.itemId) },
          { $inc: { numInStock: parseInt(item.quantity) } }
        );
    });
  • Related