【发布时间】:2021-03-04 02:38:52
【问题描述】:
好的,我有一个用户对象:
{
posts: [
{
_id: 603f1c1b966c28291cb61d60,
title: '1111',
content: '1111',
__v: 0
},
{
_id: 603f5479c989d92fbc1d082c,
title: '222',
content: '222',
__v: 0
},
{
_id: 603f5e39ddcda01f281f8931,
title: '3333',
content: '3333',
__v: 0
}
],
_id: 603f1c14966c28291cb61d5f,
username: '1',
mail: '1@1.ru',
__v: 3
}
在包含所有帖子的主页上,我在单个帖子上单击“阅读更多”,(按钮的值是该帖子的 id,我检查过,此时一切正常)并且应该呈现带有单个完整帖子的新页面,两个值:标题和内容,简单。 这是我在 app.js 中所做的:
app.get("/posts/:postID", function(req, res) {
const postID = req.params.postID;
User.findById(req.user.id, (err, user)=>{
user.posts.find(post=>{
post._id === postID;
console.log(post);
});
});
此时日志返回所有 3 个帖子。为什么?我尝试了不同的方法,我记得,我有我需要的帖子,但仍然无法从中渲染数据。帖子页面是:
<div class="block">
<h1><%= title %></h1>
<p><%= content %></p>
</div>
});
当我尝试时:
res.render("post",{
title:post.title,
content: post.content
})
那没用。但是,如果我尝试例如:
res.render("post",{
title:req.user.posts[0].title,
content: req.user.posts[0].content
})
,这行得通。
谁能帮帮我?请记住,User.find - 来自 mongoDB 的数据,req.user - 相同的数据,但在用户登录时存储在会话中。我想从会话中呈现数据并不是那么好。但是,此时任何解决方案都是可以接受的,我堆叠得很糟糕)
【问题讨论】:
标签: javascript node.js mongodb ejs