Mongoose - chain promises

I am looking for advice on the chain of promises for the find or create function using mongodb / mongoose.

Currently, I 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 this from my API endpoint (node ​​/ express):

 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:

  • Even if the user is null from the findOne query, creation is never called
  • I'm not sure I use the correct promise style / most efficient coding style.
  • I handle errors correctly, for example, at the top level, or I need to do this at each level.

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

Thank.

UPDATE

The cause of the problem was that

self.model.create(...)

should have been (without reference to the model)

self.create(...)

, - , , .

, , 500

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

/ .

+4
2

:

  • , exec
  • , () , , : return user;

, then() ( mpromise):

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;
};

,

+2

( @EduardoRodríguez) , ! , mongoose + ES6 , - :

userSchema.statics.findByFacebookIdOrCreate = function (facebookId, name, email) {
  var User = this;
  return User.findOne({facebookId})
    .then(user => user || User.create({facebookId, name, email}));
};

... :

User.findByFacebookIdOrCreate(fbRes.id, fbRes.name, fbRes.email)
  .then(user => res.sendStatus(200).send(createTokenForUser(user))
  .catch(error => res.sendStatus(500).send({error});

: ES6 promises :

mongoose.Promise = global.Promise;

, , , ( ).

0

All Articles