2017-07-18 219 views
0

我使用MongoDB中找回我的收藏的所有:尝试发送db.collection()找到()返回到客户端Ajax请求

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

让我想返回集合后这通过res.json()函数到客户端。我怎么能回报它。

添加我的服务器端代码(使用Express和节点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查询和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>" 
    ) 
    }); 
    }); 
}); 

我将不胜感激的帮帮我。

+0

你好,首先如果你的要求只会从数据库中,那么你应该使用get方法,而不是发布数据。你可以console.log结果在你的客户端并告诉我结果吗? – kikiwie

+0

嗨,我需要将rawData对象移到客户端,它在这个服务器端代码中不适用于我。 –

回答

0

根据您的代码,您好像在您收到来自MongoDB的响应之前将响应发送给客户端,因此“预测”变量本质上是空的。而且,由于要在响应发送一个数组,使用指定者代替的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(); 
}); 
}); 
+0

非常感谢! –