【问题标题】:Fetching data from mongoDB and displaying on HTML从 mongoDB 获取数据并在 HTML 上显示
【发布时间】:2018-06-17 10:02:55
【问题描述】:

我无法理解如何从 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 页面中显示来自数据库的数据。 有什么帮助吗?

【问题讨论】:

  • 呃,有什么问题?

标签: html node.js mongodb express


【解决方案1】:

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

这里是一个使用pug的例子:

1- 安装哈巴狗

npm install pug --save

2-设置视图目录:

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

3- 设置 pug 为默认视图引擎

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);
    });
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-05
    • 2018-05-29
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多