0
app.use(bodyParser.urlencoded({extended:true}))
mongoose.connect("mongodb://localhost:27017/shopDB",{useNewUrlParser:true,useUnifiedTopology: true});

app.get("/",function(req,res){
   var dbcollections;
   mongoose.connection.db.listCollections().toArray(function(err,names){
      if(err){
         console.log(err)
      }else{
         dbcollections = names;
         console.log(dbcollections) // first
      }
   });
   console.log(dbcollections) // second
   Item.find({},function(err,docs){
      if(err){
         console.log(err)
      }else{
        
        res.render("index", {list: docs ,collections: dbcollections});
      }
   }); 
   
})

The console prints as below:

undefined
[
  {
    name: 'items',
    type: 'collection',
    options: {},
    info: { readOnly: false, uuid: [Binary] },
    idIndex: { v: 2, key: [Object], name: '_id_' }
  }
]

It seemed that the second console.log(dbcollections) runs first thus return undefined. Why did this happen?

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
coffee
  • 31
  • 3
  • Your second console.log will only execute once the callback you've supplied to `.toArray()` has executed, since this is asynchronous it won't fire right away, but rather some time later after `.toArray()` has been called – Nick Parsons Jan 31 '21 at 04:52
  • 1
    Hi! Thanks for your comment. I understand now that my problem is because of asynchronosity. I will read read more on this topic! – coffee Jan 31 '21 at 05:19
  • No worries, I also suggest this answer [How do I return the response from an asynchronous call?](https://stackoverflow.com/a/14220323) which gives a nice explanation about asynchronous code at the beginning of the answer – Nick Parsons Jan 31 '21 at 05:23
  • And acutally, my second console.log fired first before the callback executed – coffee Jan 31 '21 at 05:29

1 Answers1

0

The callback you supply to toArray() does not execute until later. So you must include the code that makes use of dbcollections inside of that callback.

app.use(bodyParser.urlencoded({extended:true}))
mongoose.connect("mongodb://localhost:27017/shopDB",{useNewUrlParser:true,useUnifiedTopology: true});

app.get("/",function(req,res){
   var dbcollections;
   mongoose.connection.db.listCollections().toArray(function(err,names){
      if(err){
         console.log(err)
      }else{
         dbcollections = names;
         console.log(dbcollections) // first
         
          Item.find({},function(err,docs){
            if(err){
               console.log(err)
            }else{

              res.render("index", {list: docs ,collections: dbcollections});
            }
         }); 
      }
   });
   
})


Amauri
  • 540
  • 3
  • 15