html - 从 mongoDB 中获取数据并显示在 HTML 上

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

最佳答案

你必须使用 template engine为了在html页面中显示数据,有很多模板引擎,你可以从中选择一个link

这是一个使用 pug 的例子:

1- 安装哈巴狗

npm install pug --save

2-设置 View 目录:

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

3- 将 pug 设置为默认 View 引擎

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

4- 在 views 文件夹中创建 history.pug

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:

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

关于html - 从 mongoDB 中获取数据并显示在 HTML 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48150072/

相关文章:

node.js - 原生 MongoDB 中的自动增量

javascript - 在网页上拖动滚动

javascript - jQuery CSS 缩放转换不起作用

javascript - Bootstrap 折叠滚动到底部问题

html - 背景颜色和子菜单在 IE 中不断切换悬停状态

mongodb - 插入项原子性

iphone - Objective-C 流媒体上传音频

javascript - 使用浏览器从服务器拉取消息来更新消息

javascript - 在 JavaScript 回调返回之前更新参数,而不使用全局变量

Mongodb 按数组元素聚合组