【问题标题】:Display all comments for each post with ExpressJs and Mongoose使用 ExpressJs 和 Mongoose 显示每个帖子的所有评论
【发布时间】:2017-02-08 12:39:25
【问题描述】:

所以我一直在制作一个“类似 instagram”的网络应用程序。 用户可以发帖(图片+描述),其他用户可以评论图片。

每个帖子都包含一组评论 ID。 每条评论都包含对其帖子的引用。

我不知道如何查询(查找所有帖子,为每个帖子获取 cmets -> 渲染视图)。

这是架构的样子

//## models/post.js
var Post = new Schema({
  author     : {type: String, required: true},
  desc       : {type: String},
  imageUrl   : {type: String},
  commentsIds: [{type:Schema.ObjectId, ref:'Comment'}],
  likes      : {type: Number, default: 0},
  created_at : {type:Date, default: Date.now}
});

//## models/comment.js
var Comment = new Schema({
  username  : {type: String, required: true},
  content   : {type: String, required: true},
  post      : {type:Schema.ObjectId, ref:'Post'},
  created_at: Date 
});

我的路由器目前是这样“工作”的,因为没有错误,但它正在输出所有帖子下的所有 cmets..而不仅仅是我想要的他们各自的帖子。

// routes.js
router.get('/', function(req, res) {
  Post.find(function(err, posts, count){
    Comment.find({post: {$in: posts}}, function ( err, comments, count ){
      res.render( 'index', {
        user: req.user,
        page : 'index',
        title : 'トップページ',
        posts : posts,
        comments : comments
      });
    });
  });
});

我读过 mongoose 使用名为 populate 的东西工作,但这不只是将所有 cmets 插入帖子中吗?我不希望发布文档成为数据密集型...

有点失落..欢迎任何帮助,谢谢。

【问题讨论】:

    标签: express mongoose pug


    【解决方案1】:

    根据您的架构,您已经在帖子中包含了引用的每条评论...作为一种良好做法,最好不要在架构中包含无限数组,特别是因为您已经在评论中引用了父帖子。

    但是,由于您的 Post 架构中已经有一个 cmets 数组,您只需执行以下操作即可在查询返回的数据中包含每条评论的完整详细信息:

      router.get('/', function(req, res) {
      Post.find({})
        .populate('commentsIds')
        .exec(function(err, posts, count){  
          res.render( 'index', {
            user: req.user,
            page : 'index',
            title : '??????',
            posts : posts
          });
      });
    });
    

    Populate 不会在您尚未存储的 mongodb 中存储任何其他内容,您当前在每个帖子中存储了一个commentIds 数组,populate 只需获取所有这些 cmets 并将它们替换到 commentIds 数组中以显示你的结果。

    【讨论】:

    • 抱歉耽搁了,直到星期一我才能回复。这非常有效,感谢您的示例,我终于明白了 refpopulate 的含义。为了清楚起见,以防有人决定将这个示例用于他们自己的项目,我不得不更改 .populate('commentsIds')comments 除此之外,一切都立即生效。谢谢你:)
    • 太好了,我也在帖子中更正了它以避免任何混淆。
    • 我有同样的问题,我尝试复制它的代码,但我仍然无法让 cmets 出现在用户的数组中。我的结构非常相似,但我无法使其工作。 Here is for more detailed,请你看看我错过了什么
    猜你喜欢
    • 2012-05-02
    • 2019-04-12
    • 2017-04-03
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2020-02-18
    • 2017-07-26
    • 2011-06-30
    相关资源
    最近更新 更多