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 });
/ .