Updating nested properties in Mongo


#1

Hey new to Meteor here and having some issues with updating nested elements in MongoDB. I have the following code being inserted into the database that I need to update.

  AllOrders.insert({
      cartId: cartId,
      status: "cart",
      name: Meteor.user().username,
      items: [{
      _id: new Meteor.Collection.ObjectID().valueOf(),
      qty: qty, 
      itemPrice: itemPrice,
      subTotal: subTotal, 
      size: size, 
      temp: temp, 
      type: type, 
      special: special, 
      blend: blend, 
      method: method}],
      date: date
      });
      }
  	},

Here’s what I have to update the quantity of items but nothing happens when the button is clicked. I’m passing in the clickedItem from a template event into this Method. Any help greatly appreciated!

'addQty': function(clickedItem){
  AllOrders.update({status:"cart", items: { $eq: {_id: clickedItem}}}, { $inc: {qty: +1}});
},

#2

You need to use $ notation for what you’re trying to do.

Have a read here: https://docs.mongodb.org/manual/reference/operator/update/positional/

It makes sense.
Your query will look like this:

AllOrders.update({status:"cart", items: { $eq: {_id: clickedItem}}}, { $inc: {'items.$.qty': 1}});

edit:
I agree with what @undeadlol1 has said. i would have created multiple collections for this.
However sometimes you only want one and you need to use $ notification.


#3

You should not nest one document inside of another.
Create another collection called “items”. Then store items inside of array by referencing their _id’s

var ITEMID = Items.insert{ // .insert method returns unique _id of new document
      qty, // notice that i use "qty" instead of "gty: gty" it's a es6 shortcut
      itemPrice,
      subTotal, 
      size, 
      temp, 
      type, 
      special, 
      blend, 
      method
}

 // if you searching by _id, you don't need to specify anything else
 // just pass _id as first parameter
         AllOrders.update( cartId,
               { $push: { items:  ITEMID } }
              });
          }

Then update only the item if you need to.

Items.update( ITEMID, {
    $inc: {qty: +1}}
}

#4

Thanks, that did indeed work! I know the structure isn’t the best when you have nested elements like that and I certainly won’t ever build a project like this again.

How would I go about adding up the nested subtotal values from multiple objects in that array? I’ve been looking at the documentation for $sum and Aggregation but I don’t quite understand how that would apply in this case. Or is there a way to just return those values into an array in javascript and just add them there?