Con*_*den -1 javascript node.js node-mongodb-native
我是node.js和MongoDB的新手,所以请耐心等待.我有一个表格,可以将细节存储到MongoDB集合中; 然后我使用.findOne(现在)查询.我基本上试图将此值传递到我的index.ejs文件中并将其显示为表的一部分.所以表格应该出现:
名称:Web浏览器中的Connor.
我查询数据库的代码:
router.get('/', function(req, res) {
res.render('admin/index');
MongoClient.connect("mongodb://localhost:27017/tickets", function(err, db) {
// Ensure we have connected
if(err) {
console.log("Cannot connect to database");
} else {
console.log("Connected to database");
}
// Create a collection to query
var collection = db.collection('tickets');
collection.findOne({name:String}, function(err, item) {
// Ensure we have found the ticket
if(err) {
console.log("There was a problem finding the ticket.");
} else {
console.log("Ticket found!");
}
});
});
});
Run Code Online (Sandbox Code Playgroud)
我的代码生成表:
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Subject</th>
<th>Message</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
Jua*_*rah 16
如果在检索文档后呈现页面,则可以通过执行以下操作将文档或其某些属性传递到模板上.你可以把它放在回调函数中来试试findOne().
res.render('admin/index', { name: item['name'] });
Run Code Online (Sandbox Code Playgroud)
然后,您将能够从EJS模板访问它,如下所示:
<td>
<%= name %>
</td>
Run Code Online (Sandbox Code Playgroud)
如果您想了解更多信息,可能需要查看本教程.