Mongoose:在find()之后填充

3

我刚开始学习mongo和node js,以下是我尝试做的事情:

API的作用是基于查询检查DB中是否存在现有条目。

  • (a) 如果没有现有文档,则创建一个新文档,填充并发送给客户端。
  • (b) 如果文档存在,则返回文档,填充并发送给客户端。

问题:在场景(a)中,创建文档后,API向客户端发送“null”。

可能原因:.populate() & .exec() 在API完成创建新文档之前运行。代码片段返回null:

console.log('Inside IF' + video_res); // returns null

什么是解决这个问题的最佳方法?
model_video.findOne( video_entry, 
        function(err, video_req) { // Send Back Object ID
            if (err) res.send(err);

        if (!video_req) { // Does not work
            console.log('-----STATUS : No Video Found');

            model_video.create(video_entry, function(err, video_res) {
                    console.log('Call back activated');
                    if (err) res.send(err);

                    console.log('Response is ' + video_res);
                    return video_res; // Does not work here!
            }); // Ends - Create
            console.log('Inside IF ' + video_res);
        } 

        else { // Works
            console.log('-----STATUS : Video Found')
            if (err) return res.send(err);
            var video_res = video_req;
            console.log('Response is ' + video_res);
            return video_res;
        };
    })
    .populate('_chirps')
    .exec(function(err, video_res) {
        if (err) return res.send(err);
        res.json(video_res);
        console.log('Final Output is ' + video_res)
    });

};

非常感谢您的帮助!

1个回答

3

回调函数exec()会在.findOne查询之后立即执行,你需要把剩余的代码放到这个回调函数里面。我已经重构了你的代码,使其更符合你想做的事情。

model_video.findOne(video_entry)
.populate('_chirps')
.exec(function(err, video_res) {
  if (err) return res.send(err);

  if (video_res) {
    console.log('-----STATUS : Video Found')
    console.log('Response is ' + video_res);
    res.json(video_res)
  }
  else {
    console.log('-----STATUS : No Video Found');

    model_video.create(video_entry, function(err, new_video_res) {
      if (err) return res.send(err);

      console.log('Response is ' + new_video_res);
      res.json(new_video_res);
    });
  }
})

1
我想给你一个巨大的拥抱!它起作用了。如果.populate()在.create()函数之后,它是如何工作的? - dmr07
2
不客气 :) 在这种情况下,populate在create之前,而不是之后。它仅影响你在开始时进行的findOne查询。 - Yuri Zarubin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接