【发布时间】:2021-03-26 18:24:31
【问题描述】:
我在 Google 上看到了关于这个主题的几个问题,但我不确定为什么其中任何一个对我有用。
我只是想通过限制和偏移传递从集合中查询数据,这似乎工作正常,但我需要一个返回总数的参数。该集合中可用的数据。
有那么难吗?我为此花费了超过 12 个小时。我一定是 Nodejs 和 mongodb 的初学者。
通过我的研究,我发现db.collection(collection_name).count())
应该返回总计数。但它显示放置它的空白对象。我再次知道它正在贬值,现在我们应该使用Collection.countDocuments or Collection.estimatedDocumentCount 。再次检查documents of mongodb。根据文件说:db.orders.countDocuments({}) 我用我的集合名称替换了订单。 db.allMinisters.countDocuments({})
我收到此错误{"error":{"message":"Cannot read property 'countDocuments' of undefined"}}。我什至使用db.collection('allMinisters').countDocuments({}),但它返回承诺并将空白对象显示为计数。
我的代码:-
mongoose.connect( url, (err, database) => {
if(err) {
return console.error(err);
}
db = database;
});
exports.getAllMinisters = (req, res, next)=>{
console.log(db.collection('allMinisters').countDocuments({}));
db.collection('allMinisters').find({}).skip(0).limit(10).toArray(function (err, docs) {
if (err) {return next(err);}
const response = {
count: db.collection('allMinisters').count(),
allMinisters: docs.map(docs=>docs),
status: 'success'
}
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(response));
});
};
我如何获得总数?
【问题讨论】:
-
使用
asyn/await或callback例如。 here