【发布时间】:2017-07-18 19:12:17
【问题描述】:
我正在使用 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 查询和 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>"
)
});
});
});
我将不胜感激。
【问题讨论】:
-
您好,首先,如果您的请求只会从 db 获取数据,那么您应该使用 get 方法而不是 post。你能在你的客户中获得 console.log 结果并告诉我结果吗?
-
嗨,我需要将 rawData 对象移动到客户端,在这个服务器端代码中它对我不起作用。
标签: javascript jquery node.js ajax mongodb