嵌套的id对象不会在猫鼬中删除

时间:2019-06-14 11:47:15

标签: node.js mongodb mongoose mongoose-schema

您好,我正在尝试从文档数组中删除推送的(数据)_id,但是执行时没有任何响应。

此外,由于它是我试图删除的关系_id。如何从实际存储的集合中删除?

这是我的删除路线:-

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"]);
    }
});

这是嵌套对象,看起来像:-

{
    "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
}

这是我的控制器:-

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

是否还可以从特定_id数据所在的每个集合中删除记录?

1 个答案:

答案 0 :(得分:0)

您需要找到文档并进行更新,

数据

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

查询

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

结果

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