MongoDB - 如何使用Node.js获取集合的大小?

use*_*786 5 mongoose mongodb node.js npm

我正在使用node.js编写服务器端代码,我正在尝试使用不能正常工作的count方法获取MongoDB集合大小.

这是我的代码

var mongo = require('mongodb');
var host =  "127.0.0.1";
var port = mongo.Connection.DEFAULT_PORT;

function getStock(name, callback) {

    var db = new mongo.Db("testDB", new mongo.Server(host, port, {}));
    db.open (function(error){
        console.log("We are connected! " + host + ":" +port);

        db.collection("stocks", function(error, collection){
            console.log("We have a collection");
            **var numOfDocs = db.collection('stocks').count()**
            **console.log("The num of  Docs in our collection is: ",numOfDocs)**
            collection.find({"name":name.toString()}, function(error, cursor) {
                cursor.toArray(function(error, stocks) {
                    if (stocks.length==0) {
                        //console.log("No Stocks found!");
                        callback(false);
                    }
                    else {
                        callback(stocks[0]);
                        //console.log("Found a stock -> ",stocks[0]);
                    }
                });
            });


        });
    });
}
Run Code Online (Sandbox Code Playgroud)

Leo*_*tny 6

.count()是一个异步函数,就像.find()是。

试试下面的代码:

collection.count({}, function(error, numOfDocs) {
    console.log('I have '+numOfDocs+' documents in my collection');
    // ..
});
Run Code Online (Sandbox Code Playgroud)

的第一个参数.count()应该是搜索查询。由于您想对所有文档进行计数,因此我将一个空对象{}作为搜索查询传递。