Question

var models = require('../models')
  , _ = require('underscore')
  , Restaurant = models.restaurant
  , RestaurantBranch = models.restaurant_branch;


module.exports = {
  index: function (req, res) {
    var title = 'Restaurants near you';

    RestaurantBranch.find({country: 'Ghana', region: 'Greater Accra'}, function (err, branches) {


      var results = _.map(branches, function (branch) {
        Restaurant.findById(branch._restaurantId, function (err, restaurant) {
          return {
            'restaurant': restaurant,
            'branch': branch
          };
        });
      });

      res.send(results);
    });

  }
};

I am having a problem getting _.map to work the way I want. Instead of getting a new array with objects {restaurant: restaurant, branch: branch}. I get [null, null] instead.

I have tried lodash instead of underscore and I get the same behavior.

Was it helpful?

Solution

The problem is your Restaurant.findById line. The function seems to be asynchronous; _.map is synchronous.

So, when your return your data, it's late. The iteration made by _.map is probably already finished.

For asynchronous stuff like you want, maybe you should consider using async (async.map),

Example using async:

async.map(branches, function (branch, callback) {
  Restaurant.findById(branch._restaurantId, function (err, restaurant) {
    callback(null, { restaurant: restaurant, branch: branch });
  });
}, function (err, results) {
    res.send(results);
});

OTHER TIPS

I found another way around the problem. Since I am using mongoose anyway I could easily use population to get the restaurant data instead of even using underscore/lodash.

var models = require('../models')
  , Restaurant = models.restaurant
  , RestaurantBranch = models.restaurant_branch;


module.exports = {
  index: function (req, res) {
    var title = 'Restaurants near you';

    RestaurantBranch.find({country: 'Ghana', region: 'Greater Accra'})
      .populate('_restaurantId')
      .exec(function (err, branches) {
        res.send(branches);
      });

  }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top