Reputation: 1868
I think this is simple but I can't seem to get it to work. I have two processes. One that consumes data, and then another that decorates it. They're connected by a queue service. The first one 'saves' the document and then queues the second:
// 'post' is a mongoose object
post.save(function (err) {
if (!err) {
self.decorate('post', post.service, post.id);
}
});
Service two receives the queue message, and then attempts to query the queue. But doesn't find the item. The item DOES get written, and if I rerun the queued message a few seconds later, it finds it correctly.
It looks like the second service is trying to run before the write is complete.
How do I force the Mongoose callback to wait/act synchronously? I've tried adding 'safe: true' to the connection options.
Upvotes: 4
Views: 5196
Reputation: 15333
It would also be good to handle errors as well. So the following code will serve your purpose.
yourModel.save().then(function(savedData){
// do something with saved data
}).catch(function(err){
// some error occurred while saving, like any required field missing
throw new Error(err.message);
});
If you simply want to return true/false for save then do something like,
someFunction() {
return yourModel.save().then(function(savedData){
return true;
}).catch(function(err){
return false;
});
}
Upvotes: 2
Reputation: 432
Please consider using the promise in save() method.
post.save().then(function (savedPost) {
self.decorate('post', savedPost.service, savedPost.id);
});
Upvotes: 4