简体   繁体   中英

Mongoose - Update object array with multiple objects

I have a document that contains an array of line items eg sku, description etc and i need to append a new field to it from a seperate source. This source containts the sku for matching and a second field [lineItemId]. What's the best way to update this all at once? I'd like to do it with a direct update but not sure if i need to pull the data into node, map in the lineItemId and the push the update back.

Any help would be greatly appreciated.

Collection Object in MDB

{
   _id: ....
   orderId: 1
   lineItems: [{
      sku: "sku1",
      description: "item description"
   },
   {
      sku: "sku2",
      description: "item description"
   }]
}

Second Source

[{
   sku: "sku1",
   lineItemId: "1234"
},
{
   sku: "sku2",
   lineItemId: "5678"
}
]

Desired Result

{
   _id: ....
   orderId: 1
   lineItems: [{
      sku: "sku1",
      description: "item description",
      lineItemId: "1234"
   },
   {
      sku: "sku2",
      description: "item description",
      lineItemId: "5678"
   }]
}

Use UPSERT Method

document.findOneAndUpdate({
    orderId: 1
}, { description: "item description" }, { upsert: true });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM