简体   繁体   English

Mongoose - 使用多个对象更新 object 数组

[英]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.我有一个文档,其中包含一系列行项目,例如 sku、描述等,我需要 append 从单独的来源为其添加一个新字段。 This source containts the sku for matching and a second field [lineItemId].此源包含用于匹配的 sku 和第二个字段 [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.我想通过直接更新来做到这一点,但不确定是否需要将数据拉入节点,map 在 lineItemId 中并将更新推回。

Any help would be greatly appreciated.任何帮助将不胜感激。

Collection Object in MDB MDB 中的集合 Object

{
   _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使用 UPSERT 方法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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