gpt4 book ai didi

javascript - 在 MongoDB 中使用异步/等待时,在应用游标方法之前获取文档总数?

转载 作者:可可西里 更新时间:2023-11-01 09:47:38 25 4
gpt4 key购买 nike

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

传递给 .find() 的对象最终会从查询参数中生成,因此每次计数的结果都会不同。我应该使用 promises 而不是 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); }
});

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

最佳答案

关于 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();

关于javascript - 在 MongoDB 中使用异步/等待时,在应用游标方法之前获取文档总数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54190175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com