尝试使用ajax请求将db.collection()。find()发送回客户端

时间:2017-07-18 08:02:23

标签: javascript jquery node.js ajax mongodb

我使用mongoDB通过以下方式取回我的所有馆藏:

rawData = db.collection('Forecasts').find({});

获取集合后,我想通过res.json()函数将其返回给客户端。我该怎么回事呢。

添加我的服务器端代码(使用Express和Node JS):

router.post('/forecastHistory', (req, res, next) => {
  var rawData;
  var forecasts = [];
  // Connection url
  var url = 'mongodb://localhost:27017/SimplyForecastDB';
  // Connect using MongoClient
  MongoClient.connect(process.env.MONGODB_URI || url, (err, db) => {
    if (err) {
        console.log('Unable to connect to MongoDB server.');
    }
    console.log('Connected to MongoDB server.');
    rawData = db.collection('Forecasts').find({}).forEach(function(doc) {
      //console.log(JSON.stringify(doc, undefined, 2));
      forecasts.push(doc);
    });

    db.close();
  });
  forecasts.forEach(function(doc){
    console.log(JSON.stringify(doc, undefined, 2));
  });
  res.json(forecasts);
});

在此处添加我的客户端代码(使用js query和ajax):

$("#history").click(function() {
  $.post('/forecastHistory', function(result) {
    result.forEach(function(forecast){ 
      $("#forecast").html(
        "<p class=\"lead\">" + forecast.location + "</p>" +
        "The summary of today: " + forecast.summary +
        "<br>" + "Temp: " + forecast.temperature + " C" +
        "<br>" + "It feels like: " + forecast.feelsLike + " C" +
        "<br>" + "The Humidity: " + forecast.humidity + " %" + 
        "<br>" + "Wind Speed: " + forecast.windSpeed + " km/h" +
        "<br>"
      )
    });
  });
});

我很感激帮助。

1 个答案:

答案 0 :(得分:0)

根据您的代码,您似乎在收到MongoDB的响应之前将响应发送给客户端,因此预测&#39;变量基本上是空的。并且由于您想要响应发送数组,请使用toArray而不是forEach

router.post('/forecastHistory', (req, res, next) => {
var rawData;
var forecasts = [];
// Connection url
var url = 'mongodb://localhost:27017/SimplyForecastDB';
// Connect using MongoClient
MongoClient.connect(process.env.MONGODB_URI || url, (err, db) => {
if (err) {
    console.log('Unable to connect to MongoDB server.');
}
console.log('Connected to MongoDB server.');
rawData = db.collection('Forecasts').find({}).toArray(function(err,doc) {
   if(err){
     console.log(err);
     return;
   }
  res.json(doc);
  res.end();
});

db.close();
});
});