我是mongoDB新手,无法使用Mongoose从MongoDB中的数组中删除团队对象。我给用户的收藏看起来像;

{  "orders":[],
   "teams":[
      {
         "teamname":"Team One",
         "_id":{"$oid":"566a038404ebcdc344c5136c"},
         "members":[
            {
               "firstname":"Member ",
               "lastname":"Three",`enter code here`
               "email":"[email protected]",
               "initials":"MT",
               "_id":{"$oid":"566a038404ebcdc344c5136d"}
            },
         ]
      },
      {
         "teamname":"Team Two",
         "_id":{"$oid":"566a07f404ebcdc344c51370"},
         "members":[
            {
               "firstname":"Member",
               "lastname":"Two",
               "email":"[email protected]",
               "initials":"MT",
               "_id":{"$oid":"566a07f404ebcdc344c51371"}
            },
         ]
      },
      {
         "teamname":"Team Three",
         "_id":{"$oid":"566a083504ebcdc344c51373"},
         "members":[
            {
               "firstname":"Member",
               "lastname":"Four",
               "email":"[email protected]",
               "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 }


我不太确定该怎么解释。我也尝试过不按此处建议的那样传递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


我也不知道该怎么解释。如果有人对我做错了什么或如何轻松地从我的团队中删除一个团队有任何见解,我将非常感激。

最佳答案

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

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

10-12 16:26