MongoDB使用Node.js获取集合中的文档数(count) [英] MongoDB get the number of documents (count) in a collection using Node.js

查看:798
本文介绍了MongoDB使用Node.js获取集合中的文档数(count)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在写一个函数,它应该返回一个集合中的文档数量,当我返回的值,它说undefined,这是我的代码:

I'm currently writing a function that should return the number of documents from a collection the thing is that when i'm returning the value it says undefined, Here is my code:

    var MongoClient = require('mongodb').MongoClient;


// open the connection the DB server
var dbName = "ystocks";
var port = "27017";
var host = "localhost";
var tt = "mongodb://" + host + ":" + port + "/" + dbName;
//"mongodb://localhost:27017/ystocks"
function getNumOfDocs (collectionName, host, port, dbName) {
    var tt = "mongodb://" + host + ":" + port + "/" + dbName;
    count = 0;
    MongoClient.connect(tt, function (error, db){

        if(error) throw error;
        collectionName = collectionName;
        db.collection(collectionName).count({}, function(error, numOfDocs){
            if (error) throw error;

            //print the result
            console.dir("numOfDocs: " + numOfDocs);
            count = numOfDocs;
            console.log("count is : " + count);

            // close the DB
            return numOfDocs;
            db.close();


        });// end of count

    }); // Connection to the DB
    //return count;

} // end of getNumOfDocs


var ee = getNumOfDocs ("stocks", "localhost", "27017", "ystocks");
console.log("ee is " + ee);

请帮助我。

推荐答案

以下是 应该如何

var MongoClient = require('mongodb').MongoClient;

var dbName = "ystocks";
var port = "27017";
var host = "localhost";

function getNumOfDocs (collectionName, host, port, dbName, callback) {
    MongoClient.connect("mongodb://" + host + ":" + port + "/" + dbName, function (error, db){
        if(error) return callback(err);

        db.collection(collectionName).count({}, function(error, numOfDocs){
            if(error) return callback(err);

            db.close();
            callback(null, numOfDocs);
        });
    }); 
} 

和用法

getNumOfDocs("stocks", host, port, dbName, function(err, count) {
   if (err) {
       return console.log(err.message);
   }
   console.log('number of documents', count);
});

请记住,如果你打算多次调用此函数,到数据库一次,并使用相同的连接。

Keep in mind if you are going to call this function lots of times, it is better to just connect to the database once and the use the same connection.

这篇关于MongoDB使用Node.js获取集合中的文档数(count)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆