2015-11-27 91 views
0

新增到nodejs。一直在努力解決這個基本問題。我在mongo db中有一些數據。我正在用ejs視圖引擎快速使用。我可以看到來自console.log的mongo數據輸出。我知道我可以使用以下標記在ejs模板中插入我的數據:<%= variable%>,但我似乎無法弄清楚如何在res.render代碼中呈現它。將mongo數據渲染到ejs模板

下面是從蒙戈提取數據的代碼:

MongoClient.connect(url, function (err, db) { 
    if (err) { 
    console.log('Unable to connect to the mongoDB server. Error:', err); 
    } else { 
    console.log('Connection established to', url); 


    // Get the documents collection 
    var collection = db.collection('car'); 

    // Query the collection  
    collection.find(),(function (err, result) { 
     if (err) { 
     console.log(err); 
     } else if (result.length) { 
     console.log('Found:', result); 
     } else { 
     console.log('No document(s) found with defined "find" criteria!'); 
     } 
//Close connection 
     db.close(); 
    }); 
    } 
}); 

這是渲染部分:

// index page 
app.get('/', function(req, res) { 
    res.render('pages/index', {collection: result}); 
}); 

這是EJS模板:

<h2>Cars:</h2> 
     <h3><%= result %> 

這是我在瀏覽器中看到的錯誤:

ReferenceError:結果未定義

這是非常令人沮喪的,因爲這應該是一個簡單的直接前進...我試圖做到這一點,而不使用貓鼬。

任何幫助將不勝感激。

謝謝。

回答

0

嘗試

<%= collection %> 

你必須使用KEY,而不是從JSON對象值。

希望你已經在express模塊​​中正確設置了views目錄和查看引擎。

0

有2個問題,在您的代碼:

1),你需要有一個結果對象,您可以傳遞到您的視圖:

function getResult(callback) { 
    MongoClient.connect(url, function (err, db) { 
     if (err) { 
     console.log('Unable to connect to the mongoDB server. Error:', err); 
     } else { 
     console.log('Connection established to', url); 


     // Get the documents collection 
     var collection = db.collection('car'); 

     // Query the collection  
     collection.find(),(function (err, result) { 
      if (err) { 
      console.log(err); 
      } else if (result.length) { 
      console.log('Found:', result); 
      } else { 
      console.log('No document(s) found with defined "find" criteria!'); 
      } 
      //Close connection 
      db.close(); 
      callback(err, result); 
     }); 
     } 
    }); 
} 
// index page 
app.get('/', function(req, res) { 
    var result = getResult(function(err, result){ 
     //handle err, then you can render your view 
     res.render('pages/index', {collection: result}); 
    }); 

}); 

2)在你看來,你將有一個對象命名集合(不是結果):

<h2>Cars:</h2> 
    <h3><%= collection %> 
+0

謝謝。我已經將它更改爲index.ejs中的<%= collection%>,但仍然得到ReferenceError:結果未定義... –

+0

好的,我錯過了您爲回調添加的代碼。我已經修改了我的app.js中的代碼。我連接到數據庫(如console.log輸出所示),但瀏覽器掛在那裏http:// localhost:8080,然後不連接... –

+0

以下是集成了getResult回調函數的新代碼: –