【问题标题】:how to update a data in nested object如何更新嵌套对象中的数据
【发布时间】:2020-05-15 20:48:54
【问题描述】:

我想使用 mongoose 更新嵌套对象中的数据。我的模型是这样的:

{
  _id: 123,
  shoppingCart: [{
    _id: 321,
    totalPrice: 110,
    itemCount: 1,
    items: [{
      title: "product123",
      quantity: 2
    }]
  }]
}

我想更新购物车的商品数量。我阅读了文件,但我不明白如何更新数量?

【问题讨论】:

  • 暂时不考虑猫鼬,可以像 obj.shoppingCart[0].items[0].quantity = 3; 一样更改数量。不过,这看起来像是一个填充的数据库结果,所以我认为这不是要走的路。

标签: javascript node.js mongodb mongoose


【解决方案1】:

如果您的数据未填充(您共享的文档保存在一个集合中):

据我所知,没有直接的方法可以做到这一点。您应该先获取文档,然后根据需要对其进行更新。这些项目是嵌套的,因此它们每个都有一个 id:

const doc = await Model.findById(docId); // or find or findOne
const item = doc.shoppingCart.items.id(itemId);
item.quantity = 10;
await doc.save();

如果您想按标题删除子文档但没有 itemId,则必须搜索项目并找到该项目的 id,像以前一样获取子文档,然后执行 item.remove() 然后 @ 987654324@:

const items = doc.shoppingCart[0].items;
const idx = items.findIndex((item) => item.title === 'product123');
const item = items.id(items[idx]._id);
item.remove();
doc.save();

最好分享你到目前为止所做的事情。然后也分享一下Model,购物车显示为数组,我觉得没有意义。

顺便说一句,猫鼬有很好的文档,这是你的好朋友: Subdocument documentation

【讨论】:

  • 如果我想删除我必须做的一个项目怎么办。例如,如果我想删除一个名为“product123”的产品,我应该写什么代码?
【解决方案2】:

你想像这样使用arrayFilters

db.collection.updateOne(
    {  
        //query to match document
    },
    { $inc: { "shoppingCart.items.$[element].quantity": 1 } }, //increase by one.
    { arrayFilters: [ { "element.title": "product123" } ] }
)

【讨论】:

    猜你喜欢
    • 2020-03-17
    • 2021-02-06
    • 2023-01-12
    • 2023-01-23
    • 2012-05-18
    • 2016-08-26
    • 1970-01-01
    • 2022-12-21
    • 2023-04-03
    相关资源
    最近更新 更多