javascriptnode.jsmongoose

Possible to export an async function from a Mongoose.js model to simulate findOne() with callback


I recently updated a large project to the newest version of Mongoose and realized that support for callbacks in findOne() have been dropped. I'm curious if anyone has recommendations for the most low-impact way to update my codebase. Currently, in my users.js model I'm using this code:

module.exports.getOne = function(query, callback) {
  User.findOne(query, callback);
}

and then calling the function like so:

User.getOne({ 'username' : username }, function(err, user) { (SOME CODE) });

Is there a way to rewrite the getOne function using the newer async method that would essentially allow me to leave all the calls as-is (i.e. allows me to simply pass function to the call that will have access to the data in findOne)? Or do I just need to bite the bullet and rewrite every call with the new format?

Any suggestions appreciated!


Solution

  • You can update your getOne method as below to keep the functionality as-is and leverage the new syntax of Mongoose queries.

    module.exports.getOne = function (query, callback) {
      User.findOne(query)
        .exec()
        .then(result => callback(null, result)) // Call the callback with the result as second parameter on success
        .catch(err => callback(err)); // Call the callback with the error on failure
    };
    

    The findOne method returns a Query which is also thenable, it is recommended to use exec() to get a better stack trace in case of errors.