簡體   English   中英

如何在MongoDB collection.find()上獲取函數值

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

當我在MongoDB / Node / Express中運行collection.find()時,我需要像這樣為我的數組返回值,但是要在回調地獄中進行操作。

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);
    }
  });

您可以嘗試使用異步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);
        }
    });
});

或使用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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM