0

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

  • Note: "WARNING: this library is no longer maintained, and may have bugs and security issues. Feel free to fork but no pull request or security alert will be answered." - it was last updated 8 years ago. – Andy Mar 04 '23 at 14:55

2 Answers2

1

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.

0

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

Tunjay
  • 110
  • 3
  • 11