1

I'm trying to use an async.each to ensure that my deep population is complete before I return the response. The issue I'm having is that the locations within the sites are never present. All I have returned are the sites from the first query. The results of the location query output to the console just fine though.

To summarise, the ID of a user is given. I then return the sites associated with that user and then populate the locations for that site.

getSitesForUser: function (req, res) {
    var _id = req.param('id');

    User.findOne({ id: _id })
        .populate('sites')
        .then(function afterFind(results) {
            if (!results) {
                return res.json({ status: 'failure', message: 'User not found' });
            }

            var sites = results.sites;

            async.each(sites, function (site, cb) {
                var locations = {};
                Locations.find({ id: site.id })
                    .then(function afterFind(locResults) {
                        //locResults outputs correctly
                        sails.log.debug(locResults);
                        site.locations = locResults;
                        cb();
                    })
                    .fail(function (err) {
                        sails.log.debug(err);
                        cb(err);
                    })
            }, function (err) {
                if (err) {
                    sails.log.debug(err);
                    return res.json({ status: 'failure', message: 'Server error' });
                } else {
                    return res.json({ status: 'success', message: 'Sites for found user', sites: sites });
                }
            });
        })
        .fail(function (err) {
            sails.log.debug(err);
            return res.json({ status: 'failure', message: 'Server error' });
        });
}

Thanks in advance.

Ben Brookes
  • 419
  • 4
  • 15

1 Answers1

0

As per Sangharsh's suggestion, toJSON() solved this issue.

var resultsJSON = results.toJSON();
var sites = resultsJSON.sites;
Ben Brookes
  • 419
  • 4
  • 15