简体   繁体   中英

How to get a function value on MongoDB collection.find()

When I run collection.find() in MongoDB/Node/Express, I need to return value for my array like this but iam in callback hell;

foursquare.getVenues(params,function(error, venues) {
    if (!error) {
      var places = [];
      venues.response.venues.forEach(function(e) {
        places.push(
          {
          obj_id:e.id,
          name:e.name,
          distance:e.distance,
          here_now:req.collection.findById(e.id) //count- i want need this value
          }
        );
      });
      res.send(places);
    }
  });

You can try to use Async https://github.com/caolan/async#each

var async = require('async');
...
foursquare.getVenues(params, function (error, venues) {
    if (!error) {
        throw err;
    }

    var places = [];
    async.each(venues.response.venues, function (e, callback) {
        db.collection.findById(e.id, function (err, res) {
            places.push({
                    obj_id: e.id,
                    name: e.name,
                    distance: e.distance,
                    here_now: res
                });
            callback()
        });
    }, function (err) {
        if (err) {
            console.log('A file failed to process');
        } else {
            console.log('All files have been processed successfully');
            res.send(places);
        }
    });
});

or Using async.map

var async = require('async');

var createArray = function (e, cb) {
    db.collection.findById(e.id,function(err,res){
        var obj = {
            obj_id: e.id,
            name: e.name,
            distance: e.distance,
            here_now: res
        }
        cb(null, obj);
    });
}


async.map(venues.response.venues, createArray, function (err, places) {
    if(err){
        throw err;
    }
    console.log(places);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM