javascript - 如何使用 Mongoose 删除对象内的子文档

标签 javascript node.js mongodb mongoose

我正在尝试使用 Mongoose 从对象中删除带有 ID 的子文档。 我试图在 Moongose 中使用更新功能,但在我运行脚本后,我得到状态“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

我该怎么做?

最佳答案

要从数组中删除元素(子文档),您需要 $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);
});

希望对你有帮助。

关于javascript - 如何使用 Mongoose 删除对象内的子文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41265930/

相关文章:

javascript - 在 MySQL 数据库中使用点 - 使用 Node 更新

node.js - 有没有办法强制 path.normalize 使用 windows/mac 路径格式?

mongodb - 如何在 MongoDB= 中的两个圆的差异内执行地理搜索

javascript - 激活时更改粘性文本的颜色

JavaScript 在同一行打开大括号

javascript - 如何访问脚本设置中的计算属性?

javascript - 从 soundcloud 接收不同文件格式的流

javascript - Node.js中的相对路径问题

java - Spring boot注入(inject)mongodb数据源

java - 查询MongoDB文档中的字段值