繁体   English   中英

如何将变量从 app.js 传递和使用到 index.ejs

[英]How do I pass and use a variable from app.js to index.ejs

为什么以我在下面尝试的方式将变量从 app.js 传递到 index.ejs 不起作用,我该如何正确地做到这一点? 我正在使用 Mongoose 和 EJS 并尝试使用console.log()将数据写入网页上的数据库中,而不是在运行提示中。

  1. (app.js 片段后跟 index.ejs 片段)
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>
  1. (app.js 片段后跟 index.ejs 片段)
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>

对于情况 (1),我在刷新页面后收到错误,说docOne is not defined ,在情况 (2) 中,使用全局变量而不是显示集合的所有内容,我得到Name: [object Object] 我确实在渲染后使用console.log(doc)验证了集合是否有信息。

我尝试了一些相关的帖子和​​修复(总结了上面显示的那些),但没有一个成功。

就像评论所暗示的那样。 我错误地传递,应该通过res.render('index', {title: "Website", docOne});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM