如何在EJS模板中获取和显示关联(引用的集合)数据?

问题描述 投票:0回答:1

我有相关的集合,如下所示。在我显示博客的EJS模板中,我还希望显示每个博客的相关评论。

Model Structure:
Blog
..title (string)
..blog (string)
..comments (Referenced Comment Model) 
....comment (string)

Comment
..comment(string)

我有以下代码来查询数据并将其传递给EJS模板:

app.get('/blog',function(req,res){
  Blog.find({},function(err,blogs){
    if(err){
      console.log('can not get blogs from db!!');
    } else {
      res.render('pages/blogs', {blogs: blogs});
    }
  });
});

虽然EJS收到的数据包含评论数据,但我无法使用以下EJS代码显示评论:

  <h2>Blog Posts</h2>
  <% blogs.forEach(function(blog){ %>
    <div>
      <h3>Title: <%= blog.title %></h3>
      <p>Blog Post: <%= blog.blog %></p>
      <p>Comments </p>
        <% blog.comments.forEach(function(blogComment){ %>
            <span><%= blogComment.comment %></span>
        <%}) %>
    </div>
  <% }) %>

当我在EJS上放下以下代码时,我可以看到相关注释的id:

<span>Comments: <%= blog.comments %> </span>

评论:5a9d070609a0f31f33b99de8,5a9d0728083d5d1f672956cb

您能解释一下我如何在EJS模板上显示注释(引用数据)吗?

express ejs
1个回答
0
投票

在仔细阅读之后,我发现在输入EJS模板之前需要填充相关数据。所以正确的数据库查询如下。请注意the).populate("comments").exec(插入:

app.get('/blog',function(req,res){
  Blog.find({}).populate("comments").exec(function(err,blogs){
    if(err){
      console.log('can not get blogs from db!!');
    } else {
      res.render('pages/blogs', {title: "All Blog Posts", blogs: blogs});
    }
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.