背景
我在 Mongoose 中有一个查询,它查找一组对象,然后返回这些对象及其总数:
var itemsPerPage = 4, pageNum = 1;
Survey.find({})
.limit(itemsPerPage)
.skip(itemsPerPage * pageNum)
.then(docs => {
if (docs.length === 0)
console.log("There are no results matching your query.");
else
DocModel.count({})
.then(number => {
console.log(JSON.stringify({number, docs}));
});
})
.catch(console.log);
为了实现这一目标,我这样做:
查找
带参数的查询- 使用
limit
和skip
从正确的页面获取结果 - 如果
docs
不为空,则启动count
查询 - 返回信息
问题
这里的问题是,由于我需要在查询中分页,因此我必须向数据库发出 2 个单独的请求(find
和 count
),这可能会非常繁重。
为了优化这一点,我想避免 count
查询,但我不知道如何做。
另一个问题是嵌套的 Promise 反模式,但这不是我现在想关注的问题。
问题
我愿意接受任何有关改进此代码的建议!
最佳答案
您可以安装mongoose paginate这使得事情变得更容易。
npm install mongoose-paginate
之后
/**
* querying for `all` {} items in `MyModel`
* paginating by second page, 10 items per page (10 results, page 2)
**/
MyModel.paginate({}, 2, 10, function(error, pageCount, paginatedResults) {
if (error) {
console.error(error);
} else {
console.log('Pages:', pageCount);
console.log(paginatedResults);
}
}
希望这对您有用。谢谢:-)
关于javascript - Mongoose:改进 find() 和 count() 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43167668/