“填充”和Mongoose / MongoDB中的父/子模型一起工作

我有一个非常简单的设置,我试图用所有属于post的评论来填充我的Mongoose JSON响应

我认为在Post上调用“populate”会返回与Post相关的所有评论,但是我得到一个空数组。 我只是不明白我做错了什么。

post.js

const mongoose = require('mongoose'); const db = require('./init'); const postSchema = new mongoose.Schema({ title: String, url: String, body: String, votes: Number, _comments: [{type: mongoose.Schema.Types.ObjectId, ref: "Comment"}] }); const Post = mongoose.model('Post', postSchema); module.exports = Post; 

comment.js

 const mongoose = require('mongoose'); const db = require('./init'); const commentSchema = new mongoose.Schema({ // post_id: post_id, _post: { type: String, ref: 'Post'}, content: String, posted: { type: Date, default: Date.now() } }); const Comment = mongoose.model('Comment', commentSchema); module.exports = Comment; 

posts.js

 router.get('/', function(req, res, next) { // An empty find method will return all Posts Post.find() .populate('_comments') .then(posts => { res.json(posts) }) .catch(err => { res.json({ message: err.message }) }) }); 

在posts.js文件中,我已经设置了一个path来创build一个评论,当一个post请求发送到posts / post_id / comments

 commentsRouter.post('/', function(req, res, next) { console.log(req.params.id) //res.json({response: 'hai'}) comment = new Comment; comment.content = req.body.content; comment._post = req.params.id comment.save((err) => { if (err) res.send(err); res.json({comment}); }); }); 

当我张贴到这条路线时,正在创build注释,并且它们使用正确的_post值创build,但是填充不会拾取它们。

例如,这篇文章已经创build,并没有填充下面的相关评论:

 { "post": { "__v": 0, "votes": 0, "body": "Test Body", "url": "Test URL", "title": "Test Title", "_id": "587f4b0a4e8c5b2879c63a8c", "_comments": [] } } { "comment": { "__v": 0, "_post": "587f4b0a4e8c5b2879c63a8c", "content": "Test Comment Content", "_id": "587f4b6a4e8c5b2879c63a8d", "posted": "2017-01-18T10:37:55.935Z" } } 

创build评论时,还必须将评论实例_id保存到post。 所以在save()callback中,你可以做类似的事情

 commentsRouter.post('/', function(req, res, next) { console.log(req.params.id) //res.json({response: 'hai'}) comment = new Comment({ content: req.body.content; _post: req.params.id }); comment.save((err, doc) => { if (err) res.send(err); Post.findByIdAndUpdate(req.params.id, { $push: { _comments: doc._id } }, { new: true }, (err, post) => { if (err) res.send(err); res.json({doc}); } ) }); });