我将数据插入mongodb,然后将页面渲染到success.ejs。在success.ejs文件中,我给了一个链接。当在同一个success.js文件中单击链接时,应该从mongodb获取数据并显示在相同的success.ejs文件中。但在加载success.ejs文件之后,在控制台中发布数据后显示holedata未定义错误消息。
我在index.js文件中的帖子数据部分
app.post('/signingin', function(req, res) {
var item = {
name: req.body.name,
title: req.body.title,
age: req.body.age
};
mongo.connect(url, function(err, db){
assert.equal(null, err);
db.collection('satyamsoft').insertOne(item, function(err, result){
assert.equal(null, err);
console.log('item inserted');
db.close();
});
});
res.render('pages/success');
//console.log(req.body);
});

我的成功。页面
!DOCTYPE html>
<html lang="en">
<% include ../partials/head %>
<title>Post Jobs | Spyeer</title>
<body>
<% include ../partials/nav %>
<section class="get">
<h2>Data Inserted</h2>
<a href="/getdata">Get Data</a>
<div>
<ul>
<% holedata.forEach(function(data) { %>
<li><%= data.this.name %> - <%= data.this.title %> - <%= data.this.age %></li>
<% }); %>
</ul>
</div>
</section>
<% include ../partials/footer %>
<% include ../partials/scripts %>
</body>
</html>
&#13;
获取index.js文件中的部分代码
app.get('/getdata', function(req, res){
var resultArray = [];
mongo.connect(url, function(err, db){
assert.equal(null, err);
var cursor = db.collection('satyamsoft').find();
cursor.forEach(function(doc, err){
assert.equal(null, err);
resultArray.push(doc);
//console.log(resultArray);
//res.render('pages/getdata', {holedata: resultArray});
}, function(){
db.close();
res.render('pages/success', {holedata: resultArray});
});
&#13;
请帮我提前谢谢。
答案 0 :(得分:0)
你只需要检查每次页面渲染时应该 holedata 为空或者使用数据而不是{
"user": [{
"cdb_id":"",
"firstname":"Tom",
"lastname":"Bradley",
"phone":14155555555,
"email":"tom@gmail.com",
"address":[{
"street":"4343 shoemaker ave",
"city":"Brea",
"zip":"92821",
"country":"USA"
}],
"authenticators":[{
"name":"Lisa Hayden",
"phone":15625555555
},{
"name":"Pavan M",
"phone":17145555555
}],
"voice_sig":"242y5-4546-555kk54-437879ek545",
"voicesig_created_time":"2017-08-02T21:27:44+0000",
"status":"verified"
}]
}
你应该写res.render('pages/success');