查找和删除嵌套级别

时间:2019-04-30 10:29:51

标签: javascript mongodb mongoose

我想查找并删除该值,我的 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({"products.id": "5cc6d9737760963ea07de411"},
{ $pull:  {"products.$.id": "5cc6d9737760963ea07de411"  })

但是它不起作用。

1 个答案:

答案 0 :(得分:2)

现在,您无需使用.dot表示法。相反,您需要使用“绝对”对象结构:

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