Mongoose:改进find()和count()查询
背景
我在Mongoose中有一个查询,find一组对象,然后将这些对象与它们的总数一起返回:
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);
要做到这一点,我做到了:
- 用参数
find
查询 - 使用
limit
和skip
从正确的页面获得结果 - 如果
docs
不为空,请启动count
查询 - 返回信息
问题
这里的问题,因为我需要在查询分页,是我必须做2个单独的请求数据库( find
和count
),这可能会非常沉重。
为了优化这个,我想避免count
查询,但我不知道如何。
另一个问题是嵌套承诺反模式,但这不是我现在要关注的问题。
题
我很乐意提供任何有关改进此代码的build议!
你可以安装mongoosepaginate ,使其更容易。
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); } }
希望为你工作。 谢谢 :-)