node.js - Mongoose :在 find() 之后填充

标签 node.js mongodb express mongoose

我是 mongo 和 node js 的新手,这是我正在尝试做的事情:

该 API 用于根据查询检查数据库中是否存在现有条目。

  • (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)
    });

};

非常感谢您的帮助!

最佳答案

回调 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);
    });
  }
})

关于node.js - Mongoose :在 find() 之后填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28101043/

相关文章:

javascript - Node.js Mongoose 静态函数没有被调用

python - Scrapy中使用多蜘蛛时如何通过管道将数据保存到MongoDB?

javascript - localhost 不输出我使用的路由器和 Controller 的 JSON

node.js - 如何创建一个安全的express.js + mongodb用户认证系统

javascript - Express 4 – 将所有路由的 HTTP 重定向到 HTTPS

javascript - 使用 Sequelize 循环

javascript - 使用函数生成器将值返回到 GraphQL Mutation 中的输出字段

mysql - MySQL更新后如何立即检索信息?

java - 将 MongoDB 服务器属性放在 context.xml 中

python - 设计 Django MongoDB 引擎外键列表