【问题标题】:Using lean + cursor with find query in Mongoose在 Mongoose 中使用精益 + 光标和查找查询
【发布时间】:2022-03-10 17:24:15
【问题描述】:

我想找到在 mongoose 中通过lea() 和 cursor 使用流的好方法。 目前这是我从 mongo 获取用户的代码,它真正创建了新的用户数组

try {
    const userList = User.find().lean().cursor();
    let users = [];

    userList.on('data', (user) => users.push(user));
    userList.on('error', () => {});
    userList.on('end', () => res.status(200).send(users));
  } catch (error) {
    console.log(error);
  }

我觉得这个解决方案有点奇怪,也许有更好的实现。

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    你可以试试for loop iterator技术:

    for await (const doc of Model.find([{ $sort: { name: 1 } }]).cursor()) {
      console.log(doc.name);
    }
    

    这里是documentation 方法和光标

    阅读 Valeriy Karpov(猫鼬作者)的 article 以更深入地了解其工作原理。

    【讨论】:

      【解决方案2】:

      看看http://highlandjs.org/。

      对于高地,代码看起来像这样(未经测试):

      var _h = require('highland');
      
      _h(User.find().lean().cursor())
      .toArray(function(users) {
        res.status(200).send(users)
      });
      

      【讨论】:

      • 我想我解决了一个问题。您的解决方案只是为不需要的东西增加了额外的复杂性和依赖性
      • @MarceliJanowski 你能分享你的解决方案作为这个问题的答案吗
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-26
      • 2018-05-18
      • 1970-01-01
      • 2020-12-14
      • 1970-01-01
      • 2014-05-21
      相关资源
      最近更新 更多