0

I'm creating a Node project cause i want to knwo how to use mongoose but i'm facing a problem right now. I'm getting an undefined variable while returing a collection from my MongoDB database. This is my code:

app.js

...
case 'index-user':
        let indexUserResponse = userController.index();
        console.log(indexUserResponse); // undefined
        break;
...

user.js (controller)

...
const index = () => {
    User.find({}, function(err, res) {
        if (err) throw err;
        return res;
    });
}
...

I know that there is a user on the database and i can see it if add a console.log(user) just before the return res; so... What is happening here? I don't get it.

enbermudas
  • 1,603
  • 4
  • 20
  • 42
  • Might not be a duplicate as the question implies that the user didn't know it is an async call – DSCH Nov 19 '18 at 08:07

1 Answers1

1

The issue is that userController.index() is an calling an async function. You should use a callback or a promise in order to fetch the data from you db. Promise example: Here we are returning a promise from the the executing the query on the Users collection.

const index = () => User.find({}).exec();

And in app.js:

case 'index-user':
        userController.index().then(result => {
          console.log(result); // as you use find there will be a list of user documents
        });
        break;

Or, you can use good old callbacks as so:

const index = (callback) => {
    User.find({}, function(err, res) {
        if (err) throw err;
        return callback(res);
    });
}

And in app.js:

case 'index-user':
        let indexUserResponse = userController.index((result) => {
          console.log(result); 
        });
        break;

When you execute it the way you do now, the console.log() runs before the index() method can execute the find() callback.

Hope it's clear enough and helps

DSCH
  • 2,146
  • 1
  • 18
  • 29