我正在尝试从一个集合中获取评论并将其链接到他们的特定帖子。
我想要做的是找到所有帖子而不是收藏品然后填写帖子集合中的每个纪念品,并在评论集合中添加匹配的评论。
我已经使用ajax请求函数将articleid设置为与post _id相同。但是我对如何在populate中正确使用匹配感到困惑。
实施例。 post _id 123,我想要所有关于articleid,123的评论,但是对于多个id不仅仅是一个。
我查看了关于填充的mongoose文档,并没有像这个例子那样深入。
array.filter(function() { return res; });
router.get('/displayPosts', (req, res) => {
Post.find({}, 'topic title url', () => {
})
.populate({
path: 'commentId',
// ---------------Where confused
// match: { postId: _id },
select: 'comment',
options: {limit: 5}
})
.sort({createdAt: 'desc'})
.then((data) => {
console.log(data);
res.send({response: data});
});
});
});
//when generating new docs
//getting this from bodyparser from button submit
const newComment = new Comments({
comment: req.body.userComment,
articleId: req.body.id
});
newComment.save();
const newArticle = new Article({
topic: data.topic,
title: data.title,
url: data.url
});
newArticle.save();
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Comments = require('./comments');
const PostSchema = new Schema({
topic: String,
title: String,
url: String,
commentId: [{type: Schema.Types.ObjectId, ref: 'Comments'}]
},
{
timestamps: true
});
const Post = mongoose.model('Post', ArticleSchema);
module.exports = Post;