0

I'm trying to create a function that will query a mongo db and then return the result, then render it on a page.

I'm just currently trying to console.log the objects to find out why this isn't working:

var getMarkets = function (marketID) {
  MongoClient.connect('mongodb://localhost:27017/test', function(err, db){
    db.collection("new-test-2", function (err, collection) {
      collection.find({"ID": parseInt(marketID, 10)}).toArray(function(err, items) {
        console.log(items);
        return items;
      });
    });
  });
};
router.get('/markets/:marketid', function(req, res, next) {
  var marketobj = getMarkets(req.params.marketid);
  console.log(marketobj);
  res.render('api', { title: 'API', marketid: marketobj });
});

The log nested inside the function works fine, but then the log inside the routing object returns undefined. What's going on here? I have a feeling it has to do with asynchronous callbacks but I'm not able to reason about it.

Thanks a ton.

Camden Clark
  • 85
  • 1
  • 6

2 Answers2

0

Mongodb connection and find operations are asynchronous functions. So you need to use callback to return result. Just return inside function doesn't work.

var getMarkets = function (marketID, callback) {
  MongoClient.connect('mongodb://localhost:27017/test', function(err, db){
    db.collection("new-test-2", function (err, collection) {
      collection.find({"ID": parseInt(marketID, 10)}).toArray(function(err, items) {
        if(err)
          callback(err)
        else {
          console.log(items);
          callback(null,items);
        }
      });
    });
  });
};
router.get('/markets/:marketid', function(req, res, next) {
  getMarkets(req.params.marketid, function (err, marketobj) {
    console.log(marketobj);
    res.render('api', { title: 'API', marketid: marketobj });
  });
});

You can use promises also.

Monisha
  • 113
  • 4
0

Use callback function to access data

    var getMarkets = function (marketID , callback) {
    MongoClient.connect('mongodb://localhost:27017/test', function(err, db){
        db.collection("new-test-2", function (err, collection) {
            collection.find({"ID": parseInt(marketID, 10)}).toArray(function(err, items) {
                console.log(items);
                //return callback
                return callback(items);
            });
        });
    });
};
router.get('/markets/:marketid', function(req, res, next) {
    getMarkets(req.params.marketid , function(marketobj){
        if(marketobj){

            console.log(marketobj);
            res.render('api', { title: 'API', marketid: marketobj });

        }else{
            // do whatever you want

            res.render('api', { title: 'API', marketid: {} });
        }
    });

});
Love-Kesh
  • 777
  • 7
  • 17