nested id object not getting deleted in mongoose

强颜欢笑 提交于 2020-01-03 01:47:12

问题


Hello I am trying to delete pushed (data) _id from a document array, but I am getting no response while executing.

Also, since it is a relational _id which I am trying to delete. How can I delete from the collection it is actually stored ?

here is my delete route:-

router.delete('/userDelete/:userId', checkAuth , (req, res, next) =>{
    if(req.userData.role2 === 'admin') {
        Admin.findOneAndDelete({_id: req.params.userId},{ $pull: { 'admins.users': {_id: req.params._id}}},{new: true}) 
        .exec()
        .then(result => {
            res.status(200).send(["Deleted"]);
        })
        .catch(err =>{
        if (err.code == 500)
                    res.status(500).send(["Didn't get deleted"]);
            else
            return next(err);
        });
    }else{
        res.send(["Unauthorized. Not deleted"]);
    }
});

This is the nested object looks like :-

{
    "admins": {
        "users": [
            "5d0364048db4957100f33fea" //<===want to delete this relational id
        ],
        "email": "1cf1eede89@himail.online",
        "password": "$2a$10$vHyGxX9P.t0/ybKcmIzkc.ZCX18oHaVnvTgJIWA2gTNzJ3TCdXS4a",
    "_id": "5d0339d5b4b28b6ddff06802",
    "companyName": "GH",
    "__v": 0
}

This is my controller :-

var admin = new Admin();
    admin.companyName = req.body.companyName;
    admin.admins = {
                    email : req.body.email,
                    password: req.body.password,
                    users : [] 
    };

Is is also possible to delete records from each and every collections where particular _id data is located ?


回答1:


You need to find the Document and update,

Data

{
    "_id" : "5d0339d5b4b28b6ddff06802",
    "admins" : {
        "users" : [
            "5d0364048db4957100f33fea"
        ]
    }
}

Query

db.users.updateOne(
    { _id: req.params.userId },
    {
        $pull: {
            "admins.users": req.params._id
        }
    }
);

Result

{
    "_id" : "5d0339d5b4b28b6ddff06802",
    "admins" : {
        "users" : [ ]
    }
}


来源:https://stackoverflow.com/questions/56597540/nested-id-object-not-getting-deleted-in-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!