J. Stott
J. Stott

Reputation: 61

Promises with Mongoose methods

I was wondering what the standard way of returning data from a Mongoose method was. From the examples I've seen online, it seems that a common way of doing this is by including a callback as an argument in the method.

So for example I might have a findFriends method on my User model

UserSchema.methods.findFriends = callback => {
  ...
  return callback(null, friends);
};

To then use this method in my application I have made things work by creating a promise. But my solution feels quite clunky and probably not a best practice. Should I be implementing promises within the method on the UserSchema? I've never seen it done like this which is why I was curious to know some other perspectives on this.

const user = User.findOne();

friendsPromise = new Promise((resolve, reject) => {
  user.findFriends((error, friends) => {
    if(! error) {
      resolve(friends);
    } else {
      reject(error);
    }
  });
});

friendsPromise.then(friends => {
  console.dir(friends);
});

Upvotes: 0

Views: 535

Answers (1)

robertklep
robertklep

Reputation: 203319

Mongoose doesn't really care what your method returns. If you want to use promises instead of callbacks, just return a promise:

UserSchema.methods.findFriends = function() { // see text
  ...
  return promiseReturningFunction();
};

Some remarks:

  • instead of using the arrow notation for methods, I would suggest using a function expression (= function() { ... }). Mongoose sets the value of this to the document instance, which would get lost if you use arrow notation;
  • Most built-in Mongoose methods return promises themselves, so promiseReturningFunction could be the result of, say, User.find({ friend : ... }).exec(). See the documentation for more info.

Upvotes: 2

Related Questions