The each method call of mongodb cursor returned an empty result.

  node.js, question

var Mongo = require(‘mongodb’).MongoClient;
var url = ‘mongodb://localhost:27017/test’

var handler=function(){}
handler.prototype.queryAll=function(){

var result =[];
 Mongo.connect(url,function(err,db){
 var cursor = db.collection("mydb").find();
 cursor.each(function(err,doc){
 if(doc)
 result.push(doc)
 })
 db.close()
 })
 // return result

bracket

module.exports = handler

The each method seems to be asynchronous, and there is no way to judge whether the query has ended, so return result is empty.

Db.close () was executed first.

Judging whether doc is valid or not, if it is invalid, the traversal is finished and db is closed.
Mongo.connect(url,function(err,db){

var cursor = db.collection("mydb").find();
 cursor.each(function(err,doc){
 if(!  doc)db.close();
 
 if(doc)
 result.push(doc)
 })

})