繁体   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