[英]trying to send db.collection().find() back to client with ajax request
我正在使用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>"
)
});
});
});
我會很感激的。
根據您的代碼,似乎您是在從MongoDB獲得響應之前將響應發送到客戶端,因此'forecasts'變量實際上是空的。 並且由於要發送一個數組作為響應,因此請使用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();
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.