通过ID查找和删除猫鼬数组中的子文档

时间:2019-10-10 12:17:51

标签: node.js mongodb mongoose

我正试图用Mongoose删除数组中的子文档。

我的数据:

{
    "_id": {
        "$oid": "5d88dfe45feb4c06a5cfb762"
    },
    "spaces": [{
        "_id": {
            "$oid": "5d88dfe45feb4c06a5cfb76f"
        },
        "name": "Building 2",
        "subSpace": [{
            "_id": {
                "$oid": "5d88dfe45feb4c06a5cfb771"
            },
            "name": "Basement"
        }, {
            "_id": {
                "$oid": "5d88dfe45feb4c06a5cfb770"
            },
            "name": "Floors"
        }]
    }, {
        "_id": {
            "$oid": "5d88dfe45feb4c06a5cfb76c"
        },
        "name": "Building 4",
        "subSpace": [{
            "_id": {
                "$oid": "5d88dfe45feb4c06a5cfb76e"
            },
            "name": "Basement"
        }, {
            "_id": {
                "$oid": "5d88dfe45feb4c06a5cfb76d"
            },
            "name": "Floors"
        }]
    }]
}

对于此示例,我们要使用此_id删除 2号楼中的子空间楼层 5d88dfe45feb4c06a5cfb771

我的代码(在模型中):

exports.removeSubSpaceById = (subSpaceId) => {
    Residence.findOneAndUpdate( { "spaces.subSpace._id": '5d88dfe45feb4c06a5cfb771' },
        { $pull: 
        { spaces: 
        { subSpace: 
        { _id: '5d88dfe45feb4c06a5cfb771' }}}}, function(err, result) {
            console.log(result);
    })
};

输出:console.log:我的整个文档 但是subSpace / Basement( 5d88dfe45feb4c06a5cfb771 )仍在我的文档中。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

使用位置运算符进行嵌套数组操作。 MongoDb Docs

exports.removeSubSpaceById = (subSpaceId) => {
Residence.findOneAndUpdate({ "spaces._id": '5d88dfe45feb4c06a5cfb76f' },
    {
        $pull:
        {
            "spaces.$.subSpace": { _id: "5d88dfe45feb4c06a5cfb771" }
        }
    }, function (err, result) {
        console.log(result);
    })

}