Home > Net >  Access variables outside Mongoose query
Access variables outside Mongoose query

Time:09-22

I'm trying to query all users with Mongoose, and pass them into res.render() to be able to display them on the ejs file.

Here is my code:

const customersView = (req, res) => {

    const emailsArr = [];

    User.find({}, function(err, users) {
        users.forEach(function(user) {
            emailsArr.push(user.email);
        });

        console.log('Inside: '   emailsArr);
        // I can put res.render() here
    });

    console.log('Outside: '   emailsArr);

    // But I have to do some more queries here and then send them back all at once

    res.render('customers.ejs', {users: emailsArr});
}

However the emailsArr is empty outside of the User.find().

The console output:

[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
Server started
Connected to MongoDB
Outside: 
Inside: test@test,admin@admin

I can put res.render() inside the find() but the problem is I need to have some more query after this User query and then pass all the results to the ejs at once. How can I fix this?

CodePudding user response:

The problem is that the "outside" code is executing before because User.find is a callback, so it doesn't execute until it has the users, which is why it doesn't execute until it has the user.

const customersView = async (req, res) => {

  const emailsArr = [];

  const users = await User.find({}).catch(err => {
      // handle error here
  });

  //Your stuff
  users.forEach(function(user) {
    emailsArr.push(user.email);
  });

  console.log('Outside: '   emailsArr);

  // But I have to do some more queries here and then send them back all at once

  res.render('customers.ejs', {users: emailsArr});
}

Change the customersView function to asynchronous and use await in User.find

  • Related