Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force mongoose.save callback to wait for write to complete

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.

like image 664
Wandering Digital Avatar asked Oct 17 '25 17:10

Wandering Digital


1 Answers

Please consider using the promise in save() method.

post.save().then(function (savedPost) {
    self.decorate('post', savedPost.service, savedPost.id);
});
like image 77
Srihari Sridharan Avatar answered Oct 20 '25 08:10

Srihari Sridharan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!