我是一名mongoDB新手,无法使用Mongoose从MongoDB中的数组中删除团队对象。我的用户集合看起来像;
{ "orders":[],
"teams":[
{
"teamname":"Team One",
"_id":{"$oid":"566a038404ebcdc344c5136c"},
"members":[
{
"firstname":"Member ",
"lastname":"Three",`enter code here`
"email":"memberthree@team.com",
"initials":"MT",
"_id":{"$oid":"566a038404ebcdc344c5136d"}
},
]
},
{
"teamname":"Team Two",
"_id":{"$oid":"566a07f404ebcdc344c51370"},
"members":[
{
"firstname":"Member",
"lastname":"Two",
"email":"membertwo@team.com",
"initials":"MT",
"_id":{"$oid":"566a07f404ebcdc344c51371"}
},
]
},
{
"teamname":"Team Three",
"_id":{"$oid":"566a083504ebcdc344c51373"},
"members":[
{
"firstname":"Member",
"lastname":"Four",
"email":"memberfour@team.com",
"initials":"MF",
"_id":{"$oid":"566a083504ebcdc344c51374"}
},
]
}
],
}
我的移除路线看起来像;
exports.getTeamDelete = function(req, res) {
User.findById(req.user.id, function(err, user) {
if (err) return next(err);
var selectedTeamIndex;
for (i = 0; i < user.teams.length; i++){
if (user.teams[i]._id==req.params.teamid){
selectedTeamIndex=i;
break
}
}
console.log("before", user.teams)
console.log(req.params.teamid)
teamID=req.params.teamid;
userID=req.user.id;
User.update(
{'_id': userID},
{ $pull: { "teams" : { teamID } } },
{ multi: true },
function(err, data){
console.log(err, data);
}
);
user.markModified("teams");
user.save(function(err) {
console.log("after", user.teams)
if (err) return next(err);
req.flash('success', { msg: 'Team deleted' });
});
});
};
在User.update之前和之后的控制台日志完全相同,并且我没有抛出任何错误。 console.log(错误,数据)的输出最终为
null { ok: 1, nModified: 0, n: 1 }
我不确定如何解释。我也尝试过不按照此处的建议传递userID; https://stackoverflow.com/a/24289161/574869无效(相同的结果)。另外,我尝试将用户更新作为;
User.update(
{'_id': userID},
{ $pull: { "teams" : { id: teamID } } },
false,
true
);
如此处https://stackoverflow.com/a/15641895/574869所述,导致错误;
/Users/markbreneman/Desktop/GatherRoundApp/node_modules/mongoose/lib/query.js:2022
oldCb(error, result ? result.result : { ok: 0, n: 0, nModified: 0 });
^
TypeError: oldCb is not a function
我也不确定如何解释。如果有人对我做错了什么有任何见解,或者如何轻松地从我的团队数组中删除一个团队,我会很高兴。
答案 0 :(得分:0)
User.update(
{ "_id" : userID} ,
{ "$pull" : { "teams" : { "_id" : teamID } } } ,
{ "multi" : true }
)