dimanche 31 juillet 2016

Best Practice of using Promise with Mongoose

I'm quite new with this promise concept. I'm not sure but looking at this, I belieave I'm just using promise as callbacks and I'm ending in a promise hell!

I've this function which is suppose to get user object from MongoUser database, update it and save it again. here's my code snippet:

var changePassword = function(data){
      return new Promise(function(fulfill, reject){
        MongoUser.findOne({username: data.username}).exec()
          .then(function(mongoUser){
            mongoUser = new MongoUser();
            mongoUser.username = data.username;
            mongoUser.password = data.password;
            mongoUser.save().then(function(){
              fulfill(data);
            }).catch(function(error){
              log.error("MongoDB Failed in updating data", {"error": error});
              reject(error);
            });
          })
          .catch(function(error){
            log.error("MongoDB Failed in updating data", {"error": error});
            reject(error);
          });
      });
};

Any Idea how to use returned promise from Mongoose without creating a new one?

Aucun commentaire:

Enregistrer un commentaire