【问题标题】:Find and Update nested level查找和更新嵌套级别
【发布时间】:2019-09-18 20:09:19
【问题描述】:

我想查找 quantity 的值并将其更新为 3,其中我的 id 为“5cc6d9737760963ea07de411”

我的数据:

[
    {
        "products" : [ {
                    "id" : "5cc6d9737760963ea07de411",
                    "quantity" : 1,
                    "totalPrice" : 100,
                }, 
                {
                    "id" : "5cc6d9737760963ea07de412",
                    "quantity" : 2,
                    "totalPrice" : 200,
                }
        ],
        "isCompleted" : false,
        "_id" : "5cc7e4096d7c2c1f03570a2f"
    },
    {
        "products" : [{
                    "id" : "5cc6d9737760963ea07de414",
                    "quantity" : 1,
                    "totalPrice" : 100,
                }, 
                {
                    "id" : "5cc6d9737760963ea07de4133",
                    "quantity" : 2,
                    "totalPrice" : 200,
                }
        ],
        "isCompleted" : false,
        "_id" : "5cc7e4096d7c2c1f03570a2f"
    }

]

我试过了:

Schema.findOneAndUpdate({_id: ""},{ "products": {"quantity": 3}})

但它不起作用。

【问题讨论】:

  • 试试Schema.findOneAndUpdate({ "products.id": "5cc6d9737760963ea07de411" },{ "products": {"quantity": 3}})
  • @holydragon 删除所有产品数据并放入{"quantity": 3}
  • 添加 $set Schema.findOneAndUpdate({ "products.id": "5cc6d9737760963ea07de411" },{ $set: {"products": {"quantity": 3}}})

标签: javascript mongodb mongoose mongodb-query


【解决方案1】:

您必须在此处使用.dot 符号和$ 位置运算符

Schema.findOneAndUpdate(
  { "products.id": "5cc6d9737760963ea07de411" },
  { "products.$.quantity": 3 }
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-01
    • 2018-09-10
    • 2021-02-21
    • 1970-01-01
    • 2017-12-15
    • 2013-08-22
    • 1970-01-01
    相关资源
    最近更新 更多