从mongoDB获取数据并在HTML上显示 [英] Fetching data from mongoDB and displaying on HTML
问题描述
我在理解如何从MongoDB数据库中获取数据并将其显示在HTML上时遇到了麻烦.我已经设置好数据了.
I'm having trouble understanding how to fetch data from the MongoDB database and display it on HTML. I already have set for the data.
这是server.js文件.
this is the the server.js file.
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser')
const mongoose = require('mongoose');
const app = express();
//map global promise - get rid of warning
mongoose.Promise = global.Promise;
// connect to mongoose
mongoose.connect('mongodb://localhost/peppino-calc', {
useMongoClient: true
})
.then(() => { console.log('MongoDB connected...')})
.catch(err => console.log(err));
//Load salaryModel
require('./modles/Idea.js');
const Idea = mongoose.model('ideas');
//body parser middleware
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
// post history page
app.get('/history', (req, res) => {
Idea.find({})
.sort({date:'desc'})
res.sendFile(__dirname + '/js/newJs/history.html')
})
//process form
app.post('/ideas', (req, res) => {
let errors = [];
if(errors.length > 0) {
console.log(errors[0]);
} else {
const newUser = {
amount: req.body.totalamount,
hours: req.body.totalhours,
salary: req.body.totalsalary,
tip: req.body.totaltip,
date: req.body.datetotal
}
new Idea(newUser)
.save()
.then(idea => {
res.redirect('/history');
})
}
});
app.use(express.static(path.join(__dirname, './js/newJs')));
app.set('port', process.env.PORT || 5700);
var server = app.listen(app.get('port'), function() {
console.log('listening on port ', server.address().port);
});
我的目标是在特定的html页面中显示数据库中的数据. 有帮助吗?
my goal is to display the data from the database in a specific html page. any help?
推荐答案
您必须使用模板引擎有很多模板引擎,您可以从此
You have to use a template engine in order to display data in an html page, there are many template engines, you can choose one from this link
以下是使用 pug 的示例:
1-安装哈巴狗
npm install pug --save
2-设置视图目录:
app.set('views', path.join(__dirname, 'views'));
3-将pug设置为默认视图引擎
3- set pug as the default view engine
app.set('view engine', 'pug');
4-在views
文件夹中创建history.pug
4- create history.pug
inside views
folder
doctype html
html
head
body
table
thead
tr
th Name
th date
tbody
each idea in ideas
tr
td= idea.name
td= idea.date
5-将数据从express传递到pug:
5- pass data from express to pug:
app.get('/history', (req, res) => {
let ideas = Idea.find({})
.sort({date:'desc'}).exec( (err, ideas) => {
res.render('history', ideas);
});
})
这篇关于从mongoDB获取数据并在HTML上显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!