我正在尝试计算mongodb请求中的文档数。
我可以在count = docs.length
的回调中计算toArray()
,但总能得到10
。 A可以执行2个相同的请求,只需将find
替换为count
,但这似乎是错误的
let count;
db.get().collection('images').find({
$and: [
{tags: { $in: tags }},
{date: {$gte: date.toISOString()}},
{title:{$regex: query, $options: "$i"}},
]},
(err, docs)=>{docs.toArray((err, res)=>{
count= res.length
})}
)
.skip(0).limit(10).toArray((err, docs)=>{
res = {data:docs, dataLength:count }
cb(err, res);
// })
});
我得到这个错误:TypeError: Cannot read property 'skip' of undefined
答案 0 :(得分:0)
您可能总是会收到10笔退款,因为您在做.limit(10)
时特别说“给我10英镑”。现在,出现此错误的原因是必须将.skip
添加到.find()
的末尾。这就是查询的样子:
db.collection('images').find({
$and: [
{tags: { $in: tags }},
{date: {$gte: date.toISOString()}},
{title:{$regex: query, $options: "$i"}},
]
}).skip(0).limit(10).toArray((err, docs) => {
if (err) { console.log(err) }
else {
let res = {data:docs, dataLength:docs.length}
// do any other logic here
}
})
答案 1 :(得分:-1)
您可以使用countDocuments
db.collection('images').countDocuments({
$and: [
{tags: { $in: tags }},
{date: {$gte: date.toISOString()}},
{title:{$regex: query, $options: "$i"}},
]
}, function(err, count) {
console.log(count);
});