首页 > 解决方案 > 如何从猫鼬的嵌套对象数组中删除项目

问题描述

这就是我的“用户”数据库的样子


{
    "_id" : ObjectId("5f1408d3c0e8c130503daafd"),
    "username" : "Akhil Jagga",
    "data" : [ 
        {
            "_id" : ObjectId("5f15cde9329fc9300c7f3843"),
            "nameOfList" : "home",
            "items" : [ 
                {
                    "_id" : ObjectId("5f15cde9329fc9300c7f3844"),
                    "nameOfItem" : "this is the list item"
                }
            ]
        }, 
        {
            "_id" : ObjectId("5f15cebd9a97051d80c6c6ad"),
            "nameOfList" : "personal",
            "items" : [ 
                {
                    "_id" : ObjectId("5f15cebd9a97051d80c6c6ae"),
                    "nameOfItem" : "this is the list item"
                }, 
                {
                    "_id" : ObjectId("5f15cfd0d73dc330dc8e7fd1"),
                    "nameOfItem" : "lol"
                }
            ]
        }
    ],
    "__v" : 48
}

我想在 nodejs 中使用 mongoose 从“items”数组中删除一个特定对象,比如 ObjectId("5f15cebd9a97051d80c6c6ae")。

我尝试编写以下代码,但它不起作用:

app.post("/delete", redirectLogin, function(req, res) {
    const checkedItemId = req.body.checkbox;
    const checkedItemName = req.body.hiddenInput;
    const listName = req.body.listName;
    console.log("item id: " + checkedItemId);
    
    User.findOneAndUpdate(
        {
            username: req.session.userId
        }, 
        {
            $pull: {
                data: {
                    items: {
                        _id: checkedItemId
                    }
                }
            }
        },
        function(err, foundList) {
            console.log(foundList);
            res.redirect("/");
        });
});

感谢您的时间。

标签: node.jsmongoose

解决方案


试试这个,

const username = req.session.userId;
const listName = req.body.listName;
const checkedItemId = req.body.checkbox;

User.update({ "username": username}, { "$pull": { `data.${listName}.items`: { "_id": checkedItemId } }}, { safe: true, multi:true }, function(err, obj) {
//do rest
});

推荐阅读