Reputation: 13
What is each and forEach loop in Nodejs? I am getting my output using each but facing problem using forEach.
var MongoClient=require("mongodb").MongoClient;
var url="mongodb://localhost:27017/"
MongoClient.connect(url,function(err,db){
if(err){throw err}
var dbo=db.db("NewDataBase");
var pointer=dbo.collection("Collection").find();
pointer.each(function(err,doc){
if(err)throw err;
console.log(doc);
})
db.close();
});
Upvotes: 1
Views: 132
Reputation: 30739
pointer
is actually a reference to a cursor which you get from the query dbo.collection("Collection").find();
. And the cursor holds the set of result documents it get from that query. To access those documents you use each()
and not forEach()
. This is also because the forEach()
is a prototype function of Array type data structure but pointer
is a cursor type data structure so you cannot use that in this case.
Upvotes: 1