最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Force mongoose.save callback to wait for write to complete - Stack Overflow

programmeradmin5浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 4

Please 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;
    });
}
发布评论

评论列表(0)

  1. 暂无评论