javascript - 填充帖子 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 })
})```
非常感谢任何帮助将不胜感激。
解决方案
这个 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 })
})
推荐阅读
- php - 如何从 youtube 嵌入中删除更多视频?
- azure-devops - 在 build.yml 中设置代码覆盖率百分比
- postgresql - 如何在 postgreSQL 中加密我的密码?
- ios - 如何使用可解码的 swift 4 解析这种类型的 json 格式?
- cassandra-3.0 - 使用java从cmd打开cqlsh.bat后插入cqlsh Copy命令
- jquery - 如何获取存储在本地存储中的元素
- vba - 如何从 ComboBox 控件中获取多值字段 (MVF) 数据?
- java - 将动态生成的表单的edittext数据保存到服务器
- python - 为房地产网站建立综合抓取程序/数据库
- javascript - How to pass dynamic variable inside ng-repeat