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>"
)
});
});
});
我将不胜感激的帮帮我。
你好,首先如果你的要求只会从数据库中,那么你应该使用get方法,而不是发布数据。你可以console.log结果在你的客户端并告诉我结果吗? – kikiwie
嗨,我需要将rawData对象移到客户端,它在这个服务器端代码中不适用于我。 –