gpt4 book ai didi

arrays - 从 Mongoose/MongoDB 中的数组中删除对象

转载 作者:太空宇宙 更新时间:2023-11-03 22:32:45 25 4
gpt4 key购买 nike

我是 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(err,data) 的输出最终为

null { ok: 1, nModified: 0, n: 1 } 

我不太确定如何解释。我也尝试过不按照此处的建议传递用户ID; 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

我也不知道如何解释。如果有人对我做错了什么或者如何轻松地从我的团队数组中删除团队有任何见解,我将不胜感激。

最佳答案

User.update( 
{ "_id" : userID} ,
{ "$pull" : { "teams" : { "_id" : teamID } } } ,
{ "multi" : true }
)

关于arrays - 从 Mongoose/MongoDB 中的数组中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34215897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com