Finding Records in MongoDB from NodeJS using Cursors

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

In our last tutorial, we used findOne() to find a record in MongoDB (on MongoLabs) from NodeJS.  But what if there are more than one records to retrieve?  Using the same app code from last tutorial, we will show you how to use find() to retrieve and iterate through all records where the “state” field starts with the letter “A”.

Our query becomes …

var query = { ‘state’ : /^a/i  };

which is equivalent to …

var query = { ‘state’ : /^a.*/i };

which is equivalent to …

var query = { ‘state’ : { $regex: ‘^a.*’, $options: ‘i’ } };

The “i” means case insensitive query.

We pass that query into our find() method which returns a cursor object…

query multiple records

query multiple records

We iterate through each records in the cursor with the “each” method, which takes a callback function.  The callback function is invoke for each record in the cursor where each record is placed in “doc”.  It is only when “each” method is call that the query is run.  The query is not run at the time we instantiate the cursor.

When “doc” is not null, we accumulate the “state” field of that doc into our “answer” string.

When we encounter a null for “doc”, that means we are out of records.  We close database and render our answer string out to our homepage template.  We change the placeholder field to “data”, and we changed our homepage template to match …

hompage template

hompage template

We do console.log only for debugging purposes.  So our output looks like this …

console output

console output