0
let items = [
     {
         name: "Choco",
         id: "12344",
         qty: 24,
         status: "open"
     },
     {
         name: "Mils",
         id: "12346",
         qty: 5,
         status: "open"
     },
     {
         name: "boom",
         id: "12345",
         qty: 10,
         status: "open"
     }
 ];

Given the array above, is it possible to update the document without calling a forEach on each of them.

For instance what i am currently doing is this

  _.each(items, function( item ) {
Orders.update({_id: doc.orderId, "items.id": item.id},
                   {
                     "$set": {
                       'items.$.status': item.status,
                       'items.$.qty': item.qty,
                     }
                   })
})

is it possible to just update the entire array at once without create a new mongo db transaction

Uchenna
  • 4,059
  • 6
  • 40
  • 73
  • 1
    I found this asking the same question - http://stackoverflow.com/questions/4669178/how-to-update-multiple-array-elements-in-mongodb. It appears that you are doing it correctly from what I can find (never needed to do this). But this makes sense, how can you update all positions in an array without first knowing the length of the array? – thatgibbyguy Dec 15 '15 at 16:03
  • Why do i need to know the length of the array? – Uchenna Dec 15 '15 at 16:09
  • It's a more philosophical question. When you say "mongo, update all the positions of the array" how does mongo know how many positions are in the array? Remember, that length is likely not set in stone. So you first have to get the length of the array and from there you loop through it (as you're doing in your example). – thatgibbyguy Dec 15 '15 at 16:42

1 Answers1

0

You can read all the order:

 var order = Orders.findOne({_id: doc.orderId});

Than adjust order.items with the new data and then update in a single operation:

Orders.update({_id: doc.orderId },{"$set": {items:order.items}});

perusopersonale
  • 896
  • 1
  • 8
  • 18