我需要一些 on-hmtl-page javascript 才能访问我的 mongoDB 数据库中的数据。我使用 mongoose 从我感兴趣的集合中查找所有文档,将它们存储在数组中并将其呈现在 ejs 页面上。但我收到错误(“无效或意外的 token ”),我认为这是因为 _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 在 app.js 中的 console.logged 的样子
[ { _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 };
最佳答案
尝试将 studyHistory
渲染为 JSON 字符串
res.render('graph', {studyHistory: JSON.stringify(studyHistory)});
然后在您的 ejs 文件中解析它,如下所示:
let studyHistoryData = JSON.parse('<%- studyHistory %>');
关于node.js - 在EJS页面上访问mongoDB数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56193603/