我是 node.js 和 heroku 的新手,我构建了一个使用 node.js 并从 mongodb 实例检索一些数据的小应用程序。我设置了整个东西,但我的问题是我认为 mongodb 有一个简单的语法问题。
我需要在启动应用程序时知道我的收藏中是否有任何东西,如果没有,而不是初始化它。我尝试调用 collection.count() 但返回未定义。
我试过这样做
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 驱动程序方法(如 count
和 toArray
),通过回调函数参数而不是返回值将它们的结果异步提供给调用者,这样它们就不会阻塞单个 node.js 线程。
所以支票应该是这样的:
collection.count(function (err, count) {
if (!err && count === 0) {
populateDB();
}
});
关于node.js - Mongodb,查找集合是否为空,node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16743729/