0

So I have this API method:

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

I've also tried this to no avail:

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

When run the id printed with console.log(req.params.id);is that of a user in the database.

But also printed is error: null.

Can't figure this out, Thanks Ed.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Ed Lynch
  • 615
  • 4
  • 10
  • 28

2 Answers2

1

Try passing plain object with just the field you want to set to findByIdAndUpdate:

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

Which effectively is turned into the following update operation:

$set: { circleAlerts: alerts }}
jsalonen
  • 29,593
  • 15
  • 91
  • 109
-1

You are not specifying how to update the document, just passing the new object. Try with

User.findByIdAndUpdate({_id: req.params.id}, {$set: userTemp}, function(err, user){
   console.log("error:",err);
   res.send(user);
});
Dario
  • 6,152
  • 9
  • 39
  • 50
  • I think you would need to call `userTemp.toObject()`. Note also that this updates all fields in user document, not just `circleAlerts`. – jsalonen Aug 06 '17 at 20:36