javascript - 无法使用 ejs 路由参数和猫鼬呈现页面
问题描述
好的,我有一个用户对象:
{
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 - 相同的数据,但在用户登录时存储在会话中。我想从会话中渲染数据并不是那么好。但是,在这一点上,任何解决方案都是可以接受的,我堆得很糟糕)
解决方案
您可以在此处采用两种方法:
- 使用 if 条件并仅返回匹配的元素。
app.get("/posts/:postID", function (req, res) {
const postID = req.params.postID;
User.findById(req.user.id, (err, user) => {
user.posts.find(post => {
if (post._id === postID) {
console.log(post);
}
});
});
- 直接从查询中返回所需的元素。请原谅我冒昧地稍微修改一下代码。
const ObjectId = mongoose.Types.ObjectId; // Hoping you are using mongoose.
app.get("/posts/:postID", async function (req, res) {
try {
const postID = req.params.postID;
let post = await User.aggregate([
{
$match: {
"_id": ObjectId(req.user.id)
}
},
{
$unwind: "$posts"
},
{
$match: {
"posts._id": ObjectId(postID)
}
}
]);
if (post && post.length > 0) {
console.log(post[0])
return post; // or anyhow you want to format and return
}
} catch (exception) {
// Handle how you want.
}
});
推荐阅读
- flutter - 颤振主题
- ruby-on-rails - 创建 Active Storage 映像变体装置
- c# - $in 运算符的 C# MongoDb.Driver FilterDefinition 不起作用
- react-native - 安装“@react-navigation/web”后无法运行“expo start”命令
- node.js - NodeJS/DiscordJS UnhandledPromiseRejectionWarning 错误
- python - 如何更改饼图中标签的文本字体大小?
- console - .Net Core 5.0 如何引用与可执行文件不在同一文件夹中的json配置文件?
- r - 使用 runApp() 时如何运行所有闪亮的代码
- amazon-web-services - 检查 S3 存储桶中存在的文件的 MD5 并加载尚不存在的文件
- reactjs - 为什么我的组件在触发函数时没有改变状态