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 plete.
How do I force the Mongoose callback to wait/act synchronously? I've tried adding 'safe: true' to the connection options.
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 plete.
How do I force the Mongoose callback to wait/act synchronously? I've tried adding 'safe: true' to the connection options.
Share Improve this question asked Dec 12, 2014 at 16:03 Wandering DigitalWandering Digital 1,8682 gold badges23 silver badges28 bronze badges2 Answers
Reset to default 4Please consider using the promise in save() method.
post.save().then(function (savedPost) {
self.decorate('post', savedPost.service, savedPost.id);
});
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;
});
}