2016-12-21 67 views
5

我想從使用貓鼬的對象中刪除具有ID的子文檔。 我試圖在Moongose中使用更新功能,但運行腳本即時通訊狀態「好: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 

我該怎麼辦呢刪除子對象?

回答

3

爲了從一個數組中刪除一個元素(子文檔),你需要$pull它。

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

如果你想刪除所有的子文檔(即讓subPages是空的),你可以$set它的值是一個空數組。

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

希望它有幫助。

+0

它做到了!非常感謝你。我長久以來一直在努力。 –