2017-07-18 233 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

非常感謝! –