Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose - chaining promises

I'm looking for advice on how to chain promises for a "find or create" feature using mongodb/mongoose.

I've currently tried:

userSchema.statics.findByFacebookIdOrCreate = function(facebookId, name, email) {
  var self = this;
  return this.findOne({
    facebookId: facebookId
  }).exec().then(function(user) {
    if (!user) {
      return self.model.create({
        facebookId: facebookId,
        name: name,
        email: email
      }).exec().then(function(user) {
        return user;
      });
    }
    return user;
  });
};

And I call it from my (node/express) API endpoint:

User.model.findByFacebookIdOrCreate(fbRes.id, fbRes.name, fbRes.email)
  .then(function(user) {
    return res.sendStatus(200).send(createTokenForUser(user));
  }, function(err) {
    return res.sendStatus(500).send({
      error: err
    });
  });

Problems are though:

  1. Even though user is null from the findOne query, the create is never called
  2. I'm not sure I'm using the right promise style/most efficient coding style
  3. Am I handling errors correctly eg just at the top level or do I need to do it at every level

Can anyone see what I'm doing wrong, and how I could do it better?

Thanks.

UPDATE

The cause of the problem was that

self.model.create(...)

should have been (no model reference)

self.create(...)

However, I now need to know what I'm doing wrong with the error handling - I could see that an error was occurring, but I couldn't see the cause.

I still have some errors occurring which I know because I get a status of 500

return res.sendStatus(500).send({ error: err });

but the actual error message/detail is empty.

like image 919
prule Avatar asked Oct 31 '22 13:10

prule


1 Answers

The problem could be that:

  1. create method returns a promise and it doens't have method exec
  2. If you want to use then() in your custom method you'll have to return a promise, but you're returning a mongoose document: return user;

This will always returns a promise, it allows you to use then() after your method (You will have to add mpromise module):

userSchema.statics.findByFacebookIdOrCreate = function (facebookId, name, email) {
  var self = this;
  var Promise = require('mpromise');
  var promise = new Promise;
  this.findOne({facebookId: facebookId }).exec()
    .then(function (user) {
        if(user) {
            promise.fulfill(user);
            return;
        }

        self.model.create({ facebookId: facebookId, name: name, email: email })
            .then(function (user) {
                promise.fulfill(user);
                return;
            });
    });
  return promise;
};

Hope this helps you

like image 84
Eduardo Rodriguez Avatar answered Nov 15 '22 04:11

Eduardo Rodriguez