bersam bersam - 5 months ago 11
Javascript Question

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?

Answer

Mongoose supports promises already, so I think that you can rewrite your code to this:

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

(although I'm not sure why you are creating a user that may already exists).