【问题标题】:Trying to store mongo data in a variable and use it with hbs尝试将 mongo 数据存储在变量中并将其与 hbs 一起使用
【发布时间】:2020-07-23 01:28:03
【问题描述】:

我正在尝试将 MongoDB 数据存储在一个变量中,并使用 hbs 将其用于在 HTML 中显示。我得到的错误是 TypeError: Cannot read property 'collection' of undefined。这是我写的代码:

evar express = require('express');
var bodyParser = require('body-parser');
var mongoDB = require('mongodb').MongoClient;
var hbs = require('hbs');

var app = express();
app.use(express.static(__dirname +'/public'));

app.use( bodyParser.urlencoded());

var url = 'mongodb://localhost:27017';
var db;

mongoDB.connect(url, {useUnifiedTopology: true, useNewUrlParser: true }, function(error, client){
    if(error)
        throw error;
    db = client.db('attainu');
});

app.post('/addstudent/add', function(req, res){
    db.collection('students').insertOne(req.body, function(error, result){
        if(error)
            throw error;
        res.json(result);
        console.log("New student Successfully Added!");

    })
})

var students = db.collection('students').find({}).toArray();

app.get('/allstudents', function(req, res){
    res.render('students.hbs', {
        student: students
    });
})

app.listen(3000);

在 HTML 文件中:

<body>
{{#each student}}
<div class="card" style="width: 18rem;">
    <div class="card-body">
        <h5 class="card-title">this.name</h5>
        <p class="card-text">this.email + this.age</p>
        <a href="#" class="btn btn-primary">this.number</a>
    </div>
</div>  
{{/each}} 
</body>

我认为这是因为 JS 是异步语言。如果有人可以帮助我将其设为异步代码,那将会很有帮助。

【问题讨论】:

标签: javascript html node.js mongodb handlebars.js


【解决方案1】:

试试


app.get('/allstudents', function(req, res){
    db.collection('students').find({},(err,students)=>{
        res.render('students.hbs', {
            student: students
        });
    });  
})

【讨论】:

    【解决方案2】:
      app.get("/allstudents", async (req, res)=>{
          await db.collection("students").find({}, (error, students)=> {
          if(error) console.log(error);
          res.render("students.hbs", {
             student: students
          })
        })
      })
    

    使用异步等待数据库操作完成后再继续

    【讨论】:

      猜你喜欢
      • 2016-05-21
      • 1970-01-01
      • 2020-05-08
      • 1970-01-01
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多