将JSON var从路由传递给ejs

我在express + EJS中有一些代码,

1)在app.js中,创build了mongo集合对象,

app.locals.userCollection = db.get('userData'); 

2)在user.js表示路由文件,我从这个数据库连接获取数据,并且想把它传递给EJS来渲染,

 exports.list = function(req, res){ req.app.locals.userCollection.find({},function(err , returnValue){ if(returnValue.length>0){ res.render('user', res.locals.returnValue); } return err; }); 

};

3)在user.ejs我尝试访问它使用

 <div><script> var test = <%- returnValue %>; 

它给我returnValue是没有定义的错误。

我可以知道,如果我想访问returnValue [0] .attr1,我应该在路线和EJS代码?

关心锤子

你可以试试以下内容:

在Node.js中:

res.render('user', data: res.locals.returnValue);

在EJS:

 <script type='text/javascript'> var rows =<%-JSON.stringify(data)%> alert(rows); </script> 

更新 (根据评论中提出的问题)

如果你想遍历rows那么你不应该使用JSON.stringify()因为它将你的对象转换为String ,你可以尝试下面的代码(如果服务器放置的数据是数组对象)。

 <script type='text/javascript'> <% data.forEach(function(dataRow, idxOfRow, orgnlAryObject) { // You can directly use the dataRow to get each row from the array Object `data` //alert(JSON.stringify(dataRow)); // <== You can try this }); %> </script>