Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

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

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
    collection.find({},function(err, companies) {
                console.log (company);

However, Node returns me such error:

TypeError: Object # has no method 'forEach'

Any ideas? Thanks in advance.

Problem courtesy of: f1nn


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.

Solution courtesy of: JohnnyHK


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

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


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription