Think about the way that your router.get()
function operates. Currently, you have it written synchronously. Therefore, it will execute db.find()
and then immediately run res.render()
without waiting for the callback function being passed into db.find()
. Therefore, data
will be undefined, and you won't have the expected result.
You need to run this as an asynchronous operation. My personal preference is using try/catch
, but you can read up asynchronous JS here. That will allow for the callback function inside db.find()
to finish returning it's data.
An example (may not be working code, think of this as pseudocode):
router.get('/', async (req, res) => {
try {
var collection = [];
await db.find({}, function (err, data) {
collection = data
});
console.log(collection)
res.render('../views/Client/index.ejs', { data: collection })
} catch (err) {
console.error(err)
}
});
Here, we are telling the function to wait for db.find()
to finish its execution before running the next line res.render()
. Again, this is untested pseudocode, so don't assume copy/pasting this will work. Take the time to learn asynchronous functions.