Node.js 从EJS页面上的mongoDB访问数据
我需要一些hmtl页面javascript,以便能够从我的mongoDB数据库访问数据。我使用mongoose查找我感兴趣的集合中的所有文档,将它们存储在一个数组中,并将其呈现在ejs页面上。但是我得到了一个错误(“无效或意外标记”),我认为这是因为_id字段没有存储为字符串(它没有“/”)。我尝试了客户端和服务器端将id字段转换为字符串,但没有用。知道它为什么不是字符串,或者如何转换吗 app.jsNode.js 从EJS页面上的mongoDB访问数据,node.js,mongodb,express,mongoose,ejs,Node.js,Mongodb,Express,Mongoose,Ejs,我需要一些hmtl页面javascript,以便能够从我的mongoDB数据库访问数据。我使用mongoose查找我感兴趣的集合中的所有文档,将它们存储在一个数组中,并将其呈现在ejs页面上。但是我得到了一个错误(“无效或意外标记”),我认为这是因为_id字段没有存储为字符串(它没有“/”)。我尝试了客户端和服务器端将id字段转换为字符串,但没有用。知道它为什么不是字符串,或者如何转换吗 app.js app.get('/stats', function(req,res){ pomodo
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 %>;
尝试将
studyHistory
呈现为JSON字符串
res.render('graph', {studyHistory: JSON.stringify(studyHistory)});
然后在ejs文件中解析它,如下所示:
let studyHistoryData = JSON.parse('<%- studyHistory %>');
让studyHistoryData=JSON.parse(“”);
let studyHistoryData = JSON.parse('<%- studyHistory %>');