user3296933
user3296933

Reputation: 39

Mongodb asynchronous call?

How do you avoid asynchronous call in this case I have tried everything each time the res.render is too early and is missing objects from state. playingCollection is a mongodb collection.

var state = [];
playingCollection.find({},function(err, companies) {
    companies.each(function(err,company){
        if (company !== null) {
            var obj = company.playername;
            state.push(obj);
        }
        res.render('index', { title: 'Demo', error: req.query.error, players: state, head: 'Currently playing:'});
        state = [];
        return;
    });
});    

Upvotes: 0

Views: 126

Answers (2)

WiredPrairie
WiredPrairie

Reputation: 59763

Below is a simple way using the Cursor object returned from find. It relies only on the fact that the each call will pass a null when the list is exhausted.

var state = [];
playingCollection.find({}).each(function(err, company) {
    if (company !== null) {
        state.push(company.playername);
    } else {
        res.render('index', { title: 'Demo', error: req.query.error, players: state,  
                          head: 'Currently playing:'});
        return;
    }
});    

If you knew you were only interested in one field from the collection, you should also limit the results using the optional projection parameter:

playingCollection.find({}, { playername: 1 }).each(....);

In the above, it would return only the playername and _id field for each document.

Upvotes: 0

Hector Correa
Hector Correa

Reputation: 26680

Here is one approach to handle this using toArray after the call to find():

playingCollection.find({}).toArray(function(err, companies) {

  if(err) {
     res.render('error', {whatever});
     return;
  }

  var state = [];
  var i;
  for(i=0; i<companies.length; i++) {
      state.push(companies[i].playername);        
  }
  res.render('index', { title: 'Demo', error: req.query.error, players: state, head: 'Currently playing:'});

});

Upvotes: 1

Related Questions