So I'm making a web application and I'm trying to send variables to an EJS file but when they are sent out of the mongo functions they come out as undefined because it's a different scope for some reason. It's hard to explain so let me try to show you.
router.get("/", function(req, res){
    var bookCount;
    var userCount;
    Books.count({}, function(err, stats){
      if(err){
        console.log("Books count failed to load.");
      }else{
        bookCount = stats;
      }
    });
    User.count({}, function(err, count){
        if(err){
          console.log("User count failed to load.")
        }else{
          userCount = count;
          console.log(userCount);
        }
    });
    console.log(userCount);
    //Get All books from DB
    Books.find({}, function(err, allbooks){
        if(err){
            console.log("Problem getting all books");
        }else{
            res.render("index", {allbooks: allbooks, bookCount: bookCount, userCount: userCount});
        }
    });
});
So in the User.Count and Books.count I'm finding the number of documents in a collection which works and the number is stored inside of the variables declared at the very top.
After assigning the numbers like userCount i did console.log(userCount) which outputs the correct number which is 3, If was to do console.log(userCount) out of the User.count function it would return undefined, which is a reference to the declaration at the very top.
What is really weird is that Book.Find() has the correct userCount even though its a totally different function. The whole goal im trying to accomplish is doing res.render("index", {userCount: userCount}); outside of the Books.find(). I can do it but of course for some reason it passes undefined instead of 3. I hope this made a shred of sense.
 
     
    