Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle error when MongoDB collection is updating in JavaScript(Node.js)

I've been trying get an error when running bad code. The following code tries to update a record which has _id value 5. There is actually no such record, but I can't catch any error messages with the following function.

What should I do?

collection.update(
    { _id : "5" }, 
    // { _id : req.session.User._id }, 
    { $set: { password : req.param('password') } }, 
    { writeConcern: { w: "majority", wtimeout: 3000 } },
    function(err, result) {
        if (err) { console.log(err); return err; }

        res.send("/user/show");
    }
);
like image 476
efkan Avatar asked Jan 29 '26 18:01

efkan


1 Answers

The callback of update() has 2 arguments, err and result. When the item is updated, result is set to true, false otherwise. So when the item is not updated because item is not found, it's not considered an error, so err is null. if (err) won't be true. You need to test for updated this way:

collection.update(
  { _id : "5" }, 
  // { _id : req.session.User._id }, 
  { $set: { password : req.param('password') } }, 
  { writeConcern: { w: "majority", wtimeout: 3000 } },
  function(err, result) {
    if (err) { console.log(err); res.send(err); return;}
    if (result) {
      res.send("/user/show");
    } else {
      res.send("/user/notshow");
  }
);
like image 143
Ben Avatar answered Jan 31 '26 08:01

Ben



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!