Javascript 尝试将mongo数据存储在变量中并与hbs一起使用
我试图将MongoDB数据存储在一个变量中,并使用hbs在HTML中显示它。我得到的错误是TypeError:无法读取未定义的属性“collection”。以下是我编写的代码:Javascript 尝试将mongo数据存储在变量中并与hbs一起使用,javascript,html,node.js,mongodb,handlebars.js,Javascript,Html,Node.js,Mongodb,Handlebars.js,我试图将MongoDB数据存储在一个变量中,并使用hbs在HTML中显示它。我得到的错误是TypeError:无法读取未定义的属性“collection”。以下是我编写的代码: evar express = require('express'); var bodyParser = require('body-parser'); var mongoDB = require('mongodb').MongoClient; var hbs = require('hbs'); var app = ex
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>
{{{每个学生}
这个名字
this.email+this.age
{{/每个}}
我认为这是因为JS是异步语言。如果有人能帮我把它变成一个异步代码,那会很有帮助的 试试看
app.get('/allstudents', function(req, res){
db.collection('students').find({},(err,students)=>{
res.render('students.hbs', {
student: students
});
});
})
试一试
使用async等待数据库操作完成,然后继续
使用async等待数据库操作完成后再继续查看是否有用:查看是否有用:
app.get("/allstudents", async (req, res)=>{
await db.collection("students").find({}, (error, students)=> {
if(error) console.log(error);
res.render("students.hbs", {
student: students
})
})
})