Monday, 24 April 2017

How can I have parameters and call back functions at the same time in MongoDB update() function?

I want to have a customized callback function to check if the update() is successful and return a Q promise accordingly.

var myFunction =  function (name, email) {
  var deferred = Q.defer();

  MongoClient.connect(mongodbUrl, function (err, db) {
    var collection = db.collection('myCollection');
    collection.update(
      {'name' : name}, 
      {$set:{'email' : email}}, 
      function(err, result) {
        if (err) {
          console.log(err);
          deferred.resolve(false);
        }
        else
          //console.log(result);
          deferred.resolve(true);
      }
    );
    db.close();
  });
  return deferred.promise;
};

Then the caller is:

app.post('/abc', function(req, res) {
    myFunction(name, email)
        .then(function () {
            req.session.success = "success";
            res.redirect('/');
        })
        .fail(function (err){
          console.log(err.body);
          req.session.error = "error";
          res.redirect('/');
        });
});

First of all, the .fail() function in the caller is always executed, why?

Secondly, I also need a {upsert : true}, how can I added it to update() function while keeping the callback function?



via tic30

No comments:

Post a Comment