Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb, find if a collection is empty, node.js

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.

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.

I tried doing this

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);
  }
});

any help is appreciated.

like image 408
sleepy_ios Avatar asked May 24 '13 21:05

sleepy_ios


2 Answers

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.

So the check would go something like this:

collection.count(function (err, count) {
    if (!err && count === 0) {
        populateDB();
    }
});
like image 147
JohnnyHK Avatar answered Nov 08 '22 07:11

JohnnyHK


Great question and great answer, BUT! In case you have a lot of collections and a lot of documents inside each collection, this can take forever! We only need to know if a collection has at least one item then we can skip this collection, it's not empty... Use {limit: 1} in the options param

like image 33
Oday Avatar answered Nov 08 '22 07:11

Oday