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.
The
companiesparameter that’s passed into yourfindcallback is aCursorobject, not an array. CalltoArrayon it to convert the query results to an array of objects, oreachto process the results one at a time.