【发布时间】: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