This question already has answers here:
Mongoose: findOneAndUpdate doesn't return updated document
                                
                                    (9个答案)
                                
                        
                                2年前关闭。
            
                    
所以我有这个API方法:

router.delete('/circleAlertDelete/:id', function(req, res, next){
  User.findOne({_id: req.params.id}).then(function(user){
    var userTemp = user;
    var alerts = user.circleAlerts;
    var i = 0;
    for(i=0; i<alerts.length; i++){
      if(alerts._id == req.body.alertID){
        alerts.splice(i,1);
      }
    }
    userTemp.circleAlerts = alerts;
    console.log(req.params.id);
    User.findByIdAndUpdate({'_id': req.params.id}, userTemp, function(err, user){
      console.log("error:",err);
      res.send(user);
    });
  }).catch((err) => console.error(err));
});


我也试过了,但无济于事:

{'_id': mongo.ObjectId(req.params.id)}


运行时,用console.log(req.params.id);打印的ID是数据库中用户的ID。

而且也印有error: null

埃德,谢谢你。

最佳答案

尝试仅将要设置为findByIdAndUpdate的字段传递给普通对象:

User.findByIdAndUpdate(req.params.id, {circleAlerts: alerts}, function(err, user) {


有效地转换为以下更新操作:

$set: { circleAlerts: alerts }}

08-28 22:04