在 Mongoose 中查找和修改后不保存文档
Document not saving after finding and modifying in Mongoose
我有一个删除团队的路径以及所有加入该特定团队的请求,该路径嵌套在 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.
为什么会抛出这个错误?
首先以下一种形式进行搜索比较常见:
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);
}
})
});
}
});
我有一个删除团队的路径以及所有加入该特定团队的请求,该路径嵌套在 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.
为什么会抛出这个错误?
首先以下一种形式进行搜索比较常见:
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);
}
})
});
}
});