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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With