Mongodb,find一个集合是否为空,node.js

我是node.js和heroku的新手,我构build了一个使用node.js的小应用程序,并从mongodb实例中获取一些数据。 我设置了整个事情,但我的问题是我认为与MongoDB简单的语法问题。

我需要知道启动应用程序,我的collections有没有东西,如果没有,比初始化它。 我试着调用collection.count(),但返回undefined。

我试过这样做

mongo.connect(mongoUri, {}, function(err, database) { if(!err) { db = database; console.log("Connected to 'testdb' database, HERE"); db.collection('tests', {safe:true}, function(err, collection) { if (err) { console.log("The 'tests' collection doesn't exist. Creating it "); populateDB();//This would work for the first time I install the app on heroku } else { //Collection exists, but nothing is in it, this is where I am lost console.log("now I am HERE"); //I do not know how to mimic this piece of code //if((collection("tests").find().toArray.size() == 0 or empty or the equivalent of it) { // populateDB(); //} console.log((collection("tests").find().toArray.size())); } }); } else { console.log("COULD NOT CONNECT TO MONGO: " + mongoUri); } }); 

任何帮助表示赞赏。

任何访问数据库中的数据的MongoDB驱动程序方法(如counttoArray ),通过callback函数参数而不是通过返回值asynchronous地向调用者提供结果,以便它们不会阻塞单个node.js线程。

所以检查会是这样的:

 collection.count(function (err, count) { if (!err && count === 0) { populateDB(); } });