[英]How do I pass and use a variable from app.js to index.ejs
Why passing variables from app.js to index.ejs in the ways I tried below does not work and how do I correctly do it?为什么以我在下面尝试的方式将变量从 app.js 传递到 index.ejs 不起作用,我该如何正确地做到这一点? I am using Mongoose and EJS and trying to write the data in the database on the web-page instead of in the run prompt using console.log()
.我正在使用 Mongoose 和 EJS 并尝试使用console.log()
将数据写入网页上的数据库中,而不是在运行提示中。
app.get('/', function(req, res, next){
Review.find(function (err, doc) { // doc is an array
if (err) return console.error(err);
var docOne = doc[0]; // saving data of db in variable
res.render('index', {title: "Website"}, {docOne: docOne});
})
});
<p>Name: <%= docOne %> </p>
doc = Review.findOne();
app.get('/', function(req, res, next){
Review.find(function (err, doc) { // doc is an array
if (err) return console.error(err);
res.render('index', {title: "Website"});
})
});
<p>Name: <%= doc %> </p>
For case (1) I get an error after refreshing the page saying docOne is not defined
and in case (2) with the global variable instead of showing all the contents of the collection I get Name: [object Object]
.对于情况 (1),我在刷新页面后收到错误,说docOne is not defined
,在情况 (2) 中,使用全局变量而不是显示集合的所有内容,我得到Name: [object Object]
。 I did verify that the collection had information by using console.log(doc)
after rendering.我确实在渲染后使用console.log(doc)
验证了集合是否有信息。
There were some related posts and fixes I tried (which sum up to the ones shown above) but none of them was successful.我尝试了一些相关的帖子和修复(总结了上面显示的那些),但没有一个成功。
Just like the comment suggests.就像评论所暗示的那样。 I was passing erroneously, should be passed with res.render('index', {title: "Website", docOne});
我错误地传递,应该通过res.render('index', {title: "Website", docOne});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.