我有一个简单的网站,它的工作方式类似于当前设置的社交媒体网站我只有一个无尽的提要,我正在尝试实现无限滚动,因此帖子将在用户向下滚动时加载,而不是一次全部加载。我决定使用一个名为“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 })
})```
非常感谢任何帮助,将不胜感激。
答案 0 :(得分:1)
这个 npm 库的代码描述 populate 如下:
* @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 })
})