【问题标题】:Get total number of documents before applying cursor methods while using async/await in MongoDB?在 MongoDB 中使用 async/await 时,在应用游标方法之前获取文档总数?
【发布时间】:2019-01-14 22:32:50
【问题描述】:

如何在使用 .find() 之后和应用 .sort()、.skip() 和 .limit() 之前获取文档总数?

传递给 .find() 的对象最终将由查询参数生成,因此每次计数的结果都会不同。我应该使用 Promise 而不是 async/await 吗?

app.get('/', async (req, res) => {
  let pageSize = parseInt(req.query.limit) || 250;
  let page = parseInt(req.query.page) || 1;

  try {
    let products = await db.collection('Furniture')
      .find({})
      .sort({})
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .toArray();
    res.json({products});
  } catch (e) { console.log('Error sending products', e); }
});

应将 count 属性添加到响应中发送的 json 中,其中包含符合 find() 参数的总产品。

【问题讨论】:

    标签: javascript node.js mongodb mongodb-query


    【解决方案1】:

    find()sort()skip()limit() 最酷的地方在于它们都返回了 cursor。这意味着它们可以被链接起来,但这也意味着在任何步骤中,您都可以将光标分配给一个变量并在其上运行不同的函数,并且在完成后仍然拥有光标。

        let cursor = await db.collection('Furniture').find({})
        /* you want to wrap the following two in try catch as well, probably */
        let count = await cursor.count(); // do something with count then...
    
        let products = await cursor.sort({})
            .skip((page - 1) * pageSize)
            .limit(pageSize)
            .toArray();
    

    【讨论】:

      【解决方案2】:

      我完成的唯一方法是进行 2 次查询,一次查询柜台,另一次查询产品。

        try {
          let total = await db.collection('Furniture')
            .find({})
            .count();
      
          let products = await db.collection('Furniture')
            .find({})
            .sort({})
            .skip((page - 1) * pageSize)
            .limit(pageSize)
            .toArray();
      
          res.json({total, products});
        } catch (e) { console.log('Error sending products', e); }
      

      【讨论】:

        猜你喜欢
        • 2016-01-31
        • 1970-01-01
        • 2019-09-13
        • 1970-01-01
        • 1970-01-01
        • 2022-09-24
        相关资源
        最近更新 更多