
上一篇我們在Node.js上使用Monk模組來連結MongoDB。接著就要在Node.js程式裡把MongoDB裡的資料讀取出來。
首先打開"/routes/index.js",加入以下程式:
router.get('/userlist', function(req, res) {
    var db = req.db;
    var collection = db.get('usercollection');
    collection.find({},{},function(e,docs){
        res.render('userlist', {
            "userlist" : docs
        });
        console.log(docs);
    });
});
另外打開"views/index.hjs",另存為"views/userlist.hjs",並將內容修改如下:
    <title>User List</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  
  
    <h1>User List</h1>
    <ul>
      {{#userlist}}
      <li>{{.}}</li>
      {{/userlist}}
    </ul>
  
然後打開"localhost:3000/userlist",等網頁加載完成後,會看到console顯示的是正確的資料:
[ { _id: 54394911c4988c56a458cdd0,
    username: 'zack',
    email: 'zack@zacklive.com' },
  { _id: 54394e51c4988c56a458cdd1,
    username: 'testuser2',
    email: 'testuser2@testdomain.com' },
  { _id: 54394e51c4988c56a458cdd2,
    username: 'testuser3',
    email: 'testuser3@testdomain.com' } ]
但網頁卻顯示為:
User List
[object Object]
[object Object]
[object Object]
這是為什麼呢,我們下一篇詳細討論。
(本文同步發表於: NodeJust.com )