【问题标题】:Accessing data from mongoDB on EJS page在 EJS 页面上从 mongoDB 访问数据
【发布时间】:2019-10-05 05:03:03
【问题描述】:

我需要一些 on-hmtl-page javascript 才能访问我的 mongoDB 数据库中的数据。我使用猫鼬从我感兴趣的集合中查找所有文档,将它们存储在一个数组中并将其呈现在一个 ejs 页面上。但是我收到一个错误(“无效或意外的令牌),我认为这是因为 _id 字段没有存储为字符串(它没有“”/'')。我已经尝试过客户端和服务器端将 Id 字段转换为字符串,但无济于事。知道为什么它不是字符串或如何转换它吗?

app.js

app.get('/stats', function(req,res){
    pomodoroModel.find({}, function(err, studyHistory){
        if(err){
            console.log(err);
        }
        else{
            // send study history
            res.render('graph', {studyHistory: studyHistory});
        }
    });
});

这就是 studyHistory 的样子 console.logged in app.js

[ { _id: 5cdf0e14a4dfa719beef5cfa,
    subject: 'Math',
    timeInterval: 36142,
    __v: 0 },
{ _id: 5cdf0f5404467519d5136748,
    subject: 'History',
    timeInterval: 43322,
    __v: 0 } ]

EJS 页面

<!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function () {
let studyHistoryData = <%- studyHistory %>;

浏览器中出现错误的代码

let studyHistoryData = { _id: 5cdf0e14a4dfa719beef5cfa,
subject: 'Math',
timeInterval: 36142,
__v: 0 },{ _id: 5cdf0f5404467519d5136748,
subject: 'History',
timeInterval: 43322,
__v: 0 };

【问题讨论】:

    标签: node.js mongodb express mongoose ejs


    【解决方案1】:

    尝试将studyHistory 呈现为 JSON 字符串

    res.render('graph', {studyHistory: JSON.stringify(studyHistory)});
    

    然后像这样在你的 ejs 文件中解析它:

    let studyHistoryData = JSON.parse('<%- studyHistory %>');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-31
      • 2020-09-04
      • 2016-08-03
      相关资源
      最近更新 更多