通过nodejs从mongodb获取数据并表达为html页面 [英] Fetching data from mongodb through nodejs and express to a html page
问题描述
基本上,我想将员工"集合中的特定字段显示到html页面中.但是,即使在网上搜索了很多之后,我仍然无法做到这一点.
Basically, I want to show particular fields from "employees" collection into a html page. But even after searching a lot on web, I'm unable to do so.
这是来自server.js文件的路由部分:
Here is the route part from the server.js file:
app.get('/fetching', function(req, res){
connection.fetcher(function(data)
{
res.render("testing.html",data);
}
);
});
现在这是connection.js文件的一部分:
Now this is the part from connection.js file:
var fetcher= function(callback) {
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/HippoFeedo';
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('employees');
collection.find({},function (err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
callback(result);
}
});
}
});
现在,findOne运行正常,并将值完美返回到server.js
文件.但是我需要使用"find",那么如何通过回调将完整的数组发送到server.js
?
Now, findOne is working fine and returning the value to server.js
file perfectly. But I need to use "find", so how to send the complete array to the server.js
through callback?
此外,我需要通过渲染将从server.js
检索到的数据发送到名为testing.html
的HTML文件,并通过angular js显示它.请说明一种简单的方法.
And moreover, I need to send that retrieved data from server.js
to a HTML file called testing.html
through rendering and display it through angular js. Please explain a simple way to do so.
我知道如何使用"find",我只是在函数中使用了"toArray"和"find".现在,我可以通过回调将值返回到server.js.但是另一个问题仍然没有解决:如何将这些值传递给html页面?
I got to know how to work with "find", I just used "toArray" alongwith "find" in function. And now, I'm able to return the value to server.js through call back. But the other question is still unsolved: How do I pass those values to the html page?
推荐答案
使用ejs,您需要设置视图引擎:
Using ejs, you need to set the view engine:
app.set('view engine', 'ejs');
然后获取您的数据:
app.get('/employees',(req , res) =>{
db.collection('employees').find().toArray(function(err , i){
if (err) return console.log(err)
res.render('index.ejs',{employees: i})
})
});
.ejs文件将如下所示:
The .ejs file would be like this:
employees
<ul class="employees">
<% for(var i=0; i<employees.length; i++) {%>
<li class="employees">
<span><%= " Nome: " +employees[i].name+"."%></span>
<span><%=" Address: " + employees[i].address%></span>
</li>
<% } %>
</ul>
使用ejs的简单方法.希望它有助于澄清问题.
Just a simple way using ejs. Hope it helps to clarify things.
这篇关于通过nodejs从mongodb获取数据并表达为html页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!