Mongodb,查找集合是否为空,node.js [英] Mongodb, find if a collection is empty, node.js
问题描述
我是node.js的新手,而heroku则构建了一个使用node.js的小应用程序,并从mongodb实例中检索了一些数据.我设置了整个程序,但是我的问题是我认为mongodb的语法很简单.
I am new to node.js, and heroku, I built a small app that uses node.js and retrieves some data from a mongodb instance. I setup the whole thing but my problem is I think a simple syntactical issue with mongodb.
我需要在启动应用程序时知道我的收藏夹中是否包含任何东西(如果没有),则不进行初始化.我尝试调用collection.count(),但返回未定义.
I need to know on starting the app that my collection has any stuff in it or not, if not, than initialize it. I tried calling collection.count() but returns 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驱动程序方法(例如 toArray
),通过回调函数参数(而不是通过返回值)异步将其结果提供给调用方,以使它们不会阻塞单个节点. js线程.
Any MongoDB driver methods that access the data in the database (like count
and toArray
), provide their results to the caller asynchronously via a callback function parameter rather than via a return value so that they don't block the single node.js thread.
所以支票会像这样:
collection.count(function (err, count) {
if (!err && count === 0) {
populateDB();
}
});
这篇关于Mongodb,查找集合是否为空,node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!