从mongoDB获取数据并在HTML

时间:2018-01-08 12:13:06

标签: html node.js mongodb express

我无法理解如何从MongoDB数据库中获取数据并将其显示在HTML上。我已经设定了数据。

这是server.js文件。

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页面中显示数据库中的数据。 有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

您必须使用template engine才能在html页面中显示数据,有许多模板引擎,您可以从link中选择一个

以下是使用pug的示例:

1-安装哈巴狗

npm install pug --save

2-设置视图目录:

app.set('views', path.join(__dirname, 'views'));

3- set pug作为默认视图引擎

app.set('view engine', 'pug');

history.pug文件夹

中创建views
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-从快递传递数据到哈巴狗:

app.get('/history', (req, res) => {
    let ideas = Idea.find({})
    .sort({date:'desc'}).exec( (err, ideas) => {
        res.render('history', ideas);
    });
})