【发布时间】:2021-04-04 09:29:09
【问题描述】:
所以我的 Mongo 数据库中有一些数据,我通过快递.find() 将其发送到我的 EJS 视图。很简单。但问题是当我尝试使用<pre><%=%></pre> 阅读它时,我得到了未定义。这是整个代码:
MongoDB中包含对象的数据数组:
[{
_id: 6069820f402d01120cda8cff,
imageName: 'Dining Plate',
imagePath: './public/assets/img/6.jpg',
description: 'Wallpapers',
__v: 0
}]
我得到它并将其发送到 EJS 的表达代码:
app.get('/wallpapers/:id', ((req, res) => {
const urlID = req.params.id;
Thing.find({}, function (err, result) {
if (err) {
console.log(err);
} else {
var fres = result.filter(d => d._id == urlID);
res.render('wallpaper-page',{fres});
}
});
})
)
和 EJS:
<pre><%= fres.description%> %> </pre>
现在大混乱:当我用 fres._id 替换 fres.description 时,它工作得非常好。但就是这样,它不想打印任何其他键值。我已经搜索了将近一天。但没有任何帮助。这让我很烦。
PS: console.log(fres.description) 是 undefined 和 console.log(fres._id) 工作正常。
为什么?我该如何解决? 如果您需要任何其他代码,请告诉我。
【问题讨论】:
-
如果你必须通过 id 搜索,为什么不直接使用
Thing.findById(req.params.id)。你能告诉我console.log(fres)给了什么吗? -
findbyid 仍然会给我这个对象。 console.log(fres) 也给了我对象。
{ _id: 6069820f402d01120cda8cff, imageName: 'Dining Plate', imagePath: './public/assets/img/6.jpg', description: 'Wallpapers', __v: 0 } -
请看我的回答,如果有帮助请告诉我。 @lolman
标签: javascript node.js mongodb express ejs