首页 > 解决方案 > 填充帖子 MongoDB 的评论部分

问题描述

我有一个简单的网站,它的工作方式类似于当前设置的社交媒体网站 我决定使用一个名为“mongoose-paginate-v2”的插件来帮助对帖子进行分页。这个插件附带了一个名为 paginate 的函数。这是我下面到负责加载帖子的索引页面的路线。

router.get('/', isLoggedIn, async (req, res) => {
    const postData = await Post.paginate({}, {
        populate: {
            path: 'author'
        },

        path: 'comments',
        populate: {
            path: 'author'

        }
    });
    let posts = postData.docs;
    res.render('posts/index', { posts })
})```

这很好用,但是评论的作者没有被填充,我真的很难弄清楚为什么。每个评论都被填充了一个 ID,甚至帖子的作者也被填充了。

后架构:

const PostSchema = new Schema({
    title: String,
    images: [
        {
            url: String,
            filename: String
        }
    ],
    description: String,
    author: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    comments: [
        {
            type: Schema.Types.ObjectId,
            ref: 'Comment'
        }
    ]

});

CommentSchema: 
const commentSchema = new Schema({
    author: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    body: String
});

这是在渲染前使用 console.log(postData.docs) 时将帖子打印到控制台的示例。

 {
    comments: [
      60f88d735159d00015252440,
      60f88df35159d00015252465,
      60f88ff45159d000152524e8,
      60f899735159d000152526da
    ],
    _id: 60f88d645159d00015252432,
    title: 'First Post!',
    description: 'First SchwartzShare post.',
    images: [ [Object] ],
    author: {
      profileImage: [Object],
      _id: 60f759b470b59b0948f76db4,
      email: 'ihavebeenjamin@gmail.com',
      username: 'jam',
      __v: 1,
      description: '                                                                                                                                                                                 Fun and neat guy also really cool when you get to know me.                                        \r\n' +
        '                                        \r\n' +
        '                                        \r\n' +
        '                                        \r\n' +
        '                                        \r\n' +
        '                                        ',
      images: []
    },
    __v: 4
  },

这就是我之前实现它的方式,并且运行良好。

router.get('/', async (req, res) => {
    const posts = await Post.find({}).populate({
        path: 'comments',
        populate: {
            path: 'author',

        }
    }).populate('author');
    res.render('posts/index', { posts })
})```

非常感谢任何帮助将不胜感激。

标签: javascriptmongodb

解决方案


这个 npm 库的代码描述填充如下:

 * @param {Array|Object|String} [options.populate]

你可以试试以下吗?

router.get('/', isLoggedIn, async (req, res) => {
    const postData = await Post.paginate({}, {
        populate:[
        {path: 'author'}
       {path: 'comments', select: 'author'},
    ]}
    });
    let posts = postData.docs;
    res.render('posts/index', { posts })
})

推荐阅读