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:
- Even though user is null from the findOne query, the create is never called
- I'm not sure I'm using the right promise style/most efficient coding style
- 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.
 
     
     
    