Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS + Mongo - how to get the contents of collection?

I'm writing a simple NodeJS app with mongo. For connecting to mongo I use:

var mongo = require('mongodb'),
Server = mongo.Server,
Db = mongo.Db,
ObjectID = require('mongodb').ObjectID;
db.open(function(err,db) {...};

So, I have database "docs", and I've created a collection called "companies". Now it has 4 objects (records) in it. I want to get the full contents of this collection as an array and show them line-by-line:

//get companies list
app.get('/companies',function(req,res){
db.collection("companies",function(err,collection){
    collection.find({},function(err, companies) {
        companies.forEach(function(err,company){
                console.log (company);
            }
        );
    });
});
});

However, Node returns me such error:

TypeError: Object #<Cursor> has no method 'forEach'

Any ideas? Thanks in advance.

like image 893
f1nn Avatar asked Jun 06 '12 20:06

f1nn


1 Answers

The companies parameter that's passed into your find callback is a Cursor object, not an array. Call toArray on it to convert the query results to an array of objects, or each to process the results one at a time.

like image 181
JohnnyHK Avatar answered Nov 13 '22 07:11

JohnnyHK