簡體   English   中英

查找和計數 nodejs mongodb

[英]Find and count nodejs mongodb

我有包含數據的 mongodb 集合,例如

{"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 至於forEach僅適用於數組,這意味着迭代數組中的每個元素以執行某些操作。

例如:- [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()

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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM