2016-07-08 39 views
0

我有一個刪除團隊的路由以及加入該特定團隊的所有請求,該團隊嵌套在UserProfiles中的JoinTeamRequests數組中。這個想法是一旦刪除了該團隊的所有邀請痕跡。我正在使用MEAN堆棧。我仍然對此感到陌生,所以任何其他建議或建議都會很棒。在Mongoose中查找並​​修改文件後未保存

這裏是我的路線:

//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' 
      }); 
     }); 
    }); 
}); 

但是,我得到一個錯誤:類型錯誤:allProfiles.save不是一個函數。

爲什麼拋出這個錯誤?

+0

http://stackoverflow.com/q uestions/31341340/nodejs-mongoose-saving-model-undefined-is-not-a-function – wrxsti

回答

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); 
        } 
       }) 
      }); 
     } 
    }); 
+0

這似乎已經刪除了整個UserProfile,如果它包含JoinTeamRequest。它只是爲了移除JoinTeamRequest數組中的請求對象。 – Poot87

+0

請檢查我的更新回覆 –

相關問題