0

I have set up node and mongodb and have imported some yelp data into mongo. When I query using the mongo shell, I can see there are documents and everything is fine. However I'm unable to pass them along by adding them to an array and returning that array. When I hit up localhost:3000/api/reviews, I get a blank page. My console does log everything though so the node driver for mongo is working in getting the documents. Any ideas? I feel like it has something to do with the asynchronous nature of node.

var express = require('express');
var router = express.Router();

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var url = 'mongodb://localhost:27017/YelpDB';

var getReviews = function(db, callback) {
  var cursor = db.collection('reviews').find( );
  //JSONArray jsonarray = new JSONArray();
  var data = [];
  cursor.each(function(err, doc) {
    assert.equal(err, null);
    if (doc != null) {
      var jsonDoc = JSON.stringify(doc);
      console.log(typeof jsonDoc);
      data.push(jsonDoc);
    } else {
      callback();
    }
  });
  return data;
};

router.get('/reviews/', function(req, res, next) {
  //res.send('respond with a resource');
  MongoClient.connect(url, function(err, db) {
    assert.equal(null, err);
    var data = getReviews(db, function() {
      db.close();
    });
    res.json({"reviews": data});
  });
});

1 Answer 1

2

Please try this one, you should return the data at the end of cursor.each in the callback function.

var getReviews = function(db, callback) {
  var cursor = db.collection('reviews').find( );
  var data = [];
  cursor.each(function(err, doc) {
    if (err)
        callback(err);

    if (doc) {
      var jsonDoc = JSON.stringify(doc);
      console.log(typeof jsonDoc);
      data.push(jsonDoc);
    } else {
      // at the end of cursor, return the data through callback 
      callback(null, data);
    }
  });
};

router.get('/reviews/', function(req, res, next) {
  //res.send('respond with a resource');
  MongoClient.connect(url, function(err, db) {
    assert.equal(null, err);
    getReviews(db, function(err, data) {
        if (err)
           throw err;

        // send the data in callback function
        res.json({"reviews": data});
        db.close();
    });
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

It worked! Thanks :) Your logic for the code is better than mine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.