【问题标题】:Model.find({}) query using mongoose with node.js and express combination fails to fetch large amount of datasets of more than 200,000+ documents使用 mongoose 与 node.js 和 express 组合的 Model.find({}) 查询无法获取超过 200,000 多个文档的大量数据集
【发布时间】:2019-06-17 14:35:49
【问题描述】:

我正在使用一个简单的 get 请求,使用 mongoose 加上 express 和 node 来获取我在 MongoDB 实例中定义的特定集合中的所有文档。它适用于少量数据,但不适用于大型数据集。我能够在 Mongo Shell 上运行相同的查询,并且在相当长的一段时间后,它能够返回数据。

我尝试修改查询以使用 lean() 函数以及 mongoose 的 find({}) 函数,但问题仍然存在。

/* 
    Fetch all the players
    GET - /
*/
getPlayerRouter.route('/')
    .get((req, res, next) => {

        Player.find({}).lean()
            .then((players) => {
                res.status(200).json({
                    success: true,
                    totalPlayers: players.length,
                    players
                });
            })
            .catch((err) => console.log(err));

    });

我希望查询能够获取集合中的所有文档。

【问题讨论】:

标签: javascript node.js mongodb express mongoose


【解决方案1】:
var query=Player.find({}).stream();
query.on('data', (players)=> {
    res.status(200).json({
                      success: true,
                      totalPlayers: players.length,
                      players
                  });
 }).on('error',(err)=>{

 }).on('close',()=>{
    console.log('connection closed');
 });

你可以在mongoose中使用stream来处理大记录。评论是否有效。

【讨论】:

  • 流式传输会防止数据库端超时吗?
  • 是的,流总是更快,而且我回答中的上述代码基本上是链接异步非阻塞式调用。
  • 让我试试看。我会就此与您联系。
  • 我收到此错误。我猜标题正在以某种方式设置。错误 [ERR_HTTP_HEADERS_SENT]:发送到客户端后无法设置标头
猜你喜欢
  • 2019-05-17
  • 2017-06-05
  • 2016-06-18
  • 1970-01-01
  • 1970-01-01
  • 2020-08-11
  • 2020-12-20
  • 2020-09-24
  • 2020-01-13
相关资源
最近更新 更多