2015-11-27 92 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回调函数的新代码: –