【问题标题】:Can't render the page with ejs routing params and mongoose无法使用 ejs 路由参数和猫鼬呈现页面
【发布时间】: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


    【解决方案1】:

    您可以在这里采取两种方法:

    1. 使用 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);
          }
        });
      });
    
    1. 直接从查询中返回所需的元素。 请原谅我冒昧地稍微修改一下代码。
    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.
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      • 2016-07-14
      • 2023-03-20
      • 1970-01-01
      • 2017-11-14
      • 1970-01-01
      相关资源
      最近更新 更多