簡體   English   中英

如何使用Mongoose刪除對象內的子文檔

[英]How to remove subdocument inside of a object using Mongoose

我正在嘗試使用Mongoose從Object中刪除帶有ID的子文檔。 我試圖在Moongose中使用update fucntion但是在我運行腳本后我得到狀態“Ok:1”但狀態“nModified:0”。 試圖使用以下腳本:

 Page.update({"subPages._id": req.body.ID}, {"$unset":{"subPages":1}}, function (re,q) {
    console.log(q);
});

此腳本從對象中刪除所有子文檔。 這是我的json:

{
"_id" : ObjectId("585a7a7c2ec07b40ecb093d6"),
"name_en" : "Head Page",
"name_nl" : "Head Page",
"slug_en" : "Head-page",
"slug_nl" : "hoofd-menu",
"content_en" : "<p>Easy (and free!) You should check out our premium features.</p>",
"content_nl" : "<p>Easy (and free!) You should check out our premium features.</p>",
"date" : ISODate("2016-12-21T12:50:04.374Z"),
"is_footerMenu" : 0,
"is_headMenu" : 0,
"visible" : 1,
"__v" : 0,
"subPages" : [ 
    {
        "content_nl" : "<p>Easy (and free!) You should check out our premium features.</p>",
        "content_en" : "<p>Easy (and free!) You should check out our premium features.</p>",
        "slug_nl" : "Sub-page",
        "slug_en" : "Sub-page",
        "name_nl" : "Subpage",
        "name_en" : "Subpage",
        "date" : ISODate("2016-12-21T14:58:44.733Z"),
        "subPages" : [],
        "is_footerMenu" : 0,
        "is_headMenu" : 0,
        "visible" : 1,
        "_id" : ObjectId("585a98a46f657b52489087a8")
    }, 
    {
        "content_nl" : "<p>Easy (and free!) You should check out our premium features.</p>",
        "content_en" : "<p>Easy (and free!) You should check out our premium features.</p>",
        "slug_nl" : "Subpage",
        "slug_en" : "Subpage",
        "name_nl" : "Subpage1",
        "name_en" : "Subpage1",
        "date" : ISODate("2016-12-21T14:58:54.819Z"),
        "subPages" : [],
        "is_footerMenu" : 0,
        "is_headMenu" : 0,
        "visible" : 1,
        "_id" : ObjectId("585a98ae6f657b52489087a9")
    }
]

}

我想刪除帶ID的子對象

585a98a46f657b52489087a8

我該怎么做?

為了從數組中刪除元素(子文檔),您需要$拉它。

Page.update({
  'subPages._id': req.body.ID
}, {
  $pull: { subPages: { _id: req.body.ID } }
}, function (error, result) {
    console.log(result);
});

如果要刪除所有子文檔(即使子subPages為空),可以其值設置為空數組。

Page.update({
  'subPages._id': req.body.ID
}, {
  $set: { subPages: [] }
}, function (error, result) {
    console.log(result);
});

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM