how can I use object outside of a function in Nodejs

42 Views Asked by At

I'm Using NodeJs , why I'm not able to get the value of the data in collection variable here I'm using Nedb

router.get('/', (req, res) => {
    var collection = [];
    db.find({}, function (err, data) {
        collection = data
    });
    res.render('../views/Client/index.ejs', { data: collection })
    console.log(collection)
});

I also Try var collection =null and var collection; but still It not showing data. i have try all of these but these sill have issues. Get node.js neDB data into a variable

2

There are 2 best solutions below

0
Tunjay On

Because the callback is not being triggered before res.render(...). It is like an asynchronous operation. Your callback function can work after your database finish to find data. You can try to use res.render(...) in your callback function

0
Colin Marshall On

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.