【问题标题】:Document not saving after finding and modifying in Mongoose在 Mongoose 中查找和修改后文档未保存
【发布时间】:2016-07-08 23:23:08
【问题描述】:

我有一个删除团队和加入该特定团队的所有请求的路由,它嵌套在 UserProfiles 的 JoinTeamRequests 数组中。这个想法是在删除该团队后删除该团队的所有邀请痕迹。我正在使用 MEAN 堆栈。我还是新手,所以任何其他建议或建议都会很棒。

这是我的路线:

 //Remove a specific team
    .delete (function (req, res) {

    //Delete the team - works
    TeamProfile.remove({
        _id : req.body.TeamID
    }, function (err, draft) {
        if (err)
            res.send(err);
    });

    UserProfile.find(
        function (err, allProfiles) {

        for (var i in allProfiles) {
            for (var x in allProfiles[i].JoinTeamRequests) {
                if (allProfiles[i].JoinTeamRequests[x].TeamID == req.body.TeamID) {

                    allProfiles[i].JoinTeamRequests.splice(x, 1);
                    console.log(allProfiles[i]); //logs the correct profile and is modified
                }
            }
        }   
    }).exec(function (err, allProfiles) {
        allProfiles.save(function (err) { //error thrown here
            if (err)
                res.send(err);

            res.json({
                message : 'Team Successfully deleted'
            });
        });
    });
});

但是,我收到一个错误:TypeError: allProfiles.save is not a function。

为什么会抛出这个错误?

【问题讨论】:

标签: node.js mongodb mongoose mean-stack


【解决方案1】:

首先,以下一个形式执行搜索更为常见:

UserProfile.find({'JoinTeamRequests.TeamID': req.body.TeamID})

其次,执行后要检查返回的数组是否为空:

if(allProfiles && allProfiles.length) {

}

我认为可以在一个语句中执行此操作,但现在,请尝试下一段代码:

   UserProfile.find({'JoinTeamRequests.TeamID': req.body.TeamID}).exec(function (err, users) {
        if(err) {
            return res.end(err);
        }
        if(users && users.length) {
            users.forEach(function(user) {
                user.JoinTeamRequests.remove(req.body.TeamID);
                user.save(function(err) {
                    if(err) {
                        return res.end(err);
                    }
                })
            });
        }
    });

【讨论】:

  • 这似乎已经删除了整个 UserProfile,如果它包含 JoinTeamRequest。它仅用于删除 JoinTeamRequest 数组中的请求对象。
猜你喜欢
  • 2014-03-27
  • 2015-07-31
  • 2019-01-13
  • 2019-07-14
  • 1970-01-01
  • 1970-01-01
  • 2020-01-20
  • 2021-05-15
  • 2016-08-10
相关资源
最近更新 更多