Node.js 查找和计数nodejs mongodb
我有mongodb收集的数据,例如Node.js 查找和计数nodejs mongodb,node.js,mongodb,count,find,Node.js,Mongodb,Count,Find,我有mongodb收集的数据,例如 {"test": "test1"} {"test": "test2"} {"test": "test3"} 从数据库级别进行搜索时不会出现问题: db.collection.find({test: "test1"}).count(); 获取结果:13 但是,从nodejs级别,当我有: var counter = db.collection('collection').find({test: "test1"}).count(); coun
{"test": "test1"}
{"test": "test2"}
{"test": "test3"}
从数据库级别进行搜索时不会出现问题:
db.collection.find({test: "test1"}).count();
获取结果:13
但是,从nodejs级别,当我有:
var counter = db.collection('collection').find({test: "test1"}).count();
counter.forEach (function (doc, err) {
assert.equal (null, err);
resultArray.push (doc);
}, function () {
client.close ();
console.log ("resultArray", resultArray);
});
结果:forEach不是一个函数
我应该使用什么才能在EJS中显示该值
致以最诚挚的问候您似乎没有等待承诺的解决,
find
返回一个游标,并且没有forEach
功能
将您的线路改为此,这样可以解决问题:
var counter = await db.collection('collection').find({test: "test1"});
这是因为您的
db.collection.find({test:“test1”}).count()
返回一个数字,正如您看到的那样,您将得到13
,因为这是一个您无法对其执行.forEach
的数字。AsforEach
将只在数组上工作,这意味着迭代数组中的每个元素以执行某些操作
Ex:-[1,2,3]。forEach(i=>console.log(i))
将记录1
,2
,3
。但是,如果您将数组以外的任何内容传递给,forEach
将抛出一个与您得到的完全相同的错误
此外,您还可以更改查询和代码,以便尝试以下操作:
db.collection('collection').count({ test: "test1" }, (err, counter) => {
if (err) {/** return from here */ }
assert.equal(null, err);
console.log('Total no.of docs matched ::', counter)
resultArray.push(counter); // What is this resultArray, anyway it has to be an array ?
}, function () {
client.close();
console.log("resultArray", resultArray);
});
如果您需要所有文档及其计数,那么只需使用.find()
:
我得到的结果是:wait仅在异步函数中有效//我忘了在末尾添加.count,这实际上就是我的意思。谢谢你在我的主题中的回答。但我仍然必须在res.render中显示它(使其可用于EJS)。现在,在db.collection查询之后,resultArray对我不可用。函数()之后{client.close();我没有console.log resultaray我在路由器中有一些其他数据库查询,我在最后用res.render写下了所有内容。你能帮我吗?@Mr.Pat:你说resultaray不可用是什么意思?你还需要什么?我编辑了我的帖子,以获取代码,客户计数:resultArray 1在中不可见/list@Mr.Pat:你的代码有很多问题数量!!您到底需要什么?
database.collection('collection').aggregate([{$count:'employee\u name}]))
->不需要&员工计数光标。forEach
->->不起作用。另外,这两个DB调用必须并行!!请您将此编辑还原并保留帖子的原始内容,让我们关闭此问题,不要添加任何杂乱内容,以使问题在将来看起来干净-请提出一个包含所有必需内容的新问题:-)
db.collection('collection').find({ test: "test1" }).toArray((err, resp) => {
if (err) {/** return from here */ }
assert.equal(null, err);
/** Here resp will be an array of objects or [] */
if (resp.length) {
resultArray.concat(resp)
console.log('Total no.of docs matched ::', resp.length)
}
console.log('No docs found for given filter');
}, function () {
client.close();
console.log("resultArray", resultArray);
});