简体   繁体   中英

.push() not adding MongoDB objects to array

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

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

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