1

I want to process my data that I retreived from my mongodb, before I return it through my api.

My api-request is like this:

.get('/users', function(req, res){
    var users = [];
    User.find({}, function(err, data){
        if(err) res.send(err);
        users = data;
    }

    // here I want to do some things with the users

    res.json(users);
}

However, users got undefined... My guess is that the code runs forward, before the response got back to efectively fill 'users' What i the right way to wait until the variable is filled to be able to use the contents? Or is it not a waiting mather, but a different error?

stijnpiron
  • 359
  • 2
  • 4
  • 15
  • I am aware it would be a duplicate question, however I didn't know what to look for... (had no ID this was synchronous...) – stijnpiron Apr 15 '16 at 14:51

1 Answers1

2
User.find({}, function(err, data){
        if(err) res.send(err);
        users = data;
    }

The above code will run asynchronously, so you are expecting result before its get finished.

So try for this:

    .get('/users', function(req, res){
        var users = [];
        User.find({}, function(err, data){
            if(err) res.send(err);
            users = data;

         //  do some things with the users

        res.json(users);
        }    
}
Subburaj
  • 5,114
  • 10
  • 44
  • 87