は、私は私が呼び出すことが考え「移入」とマングース/ MongoDBの親/子モデルで作業
ポストに属するすべてのコメントと私のマングースの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ファイル内ポスト要求がポストに送信されたとき、私はコメントは、私はこのルートに投稿するときに作成されている、と彼らは正しい_POSTの値を使用して作成されている post_idの/コメント
/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});
});
});
コメントを作成するためのルートを設定しましたしかし、人口はそれを拾っていません。
たとえば、この記事が作成されました、そしてそれは、以下の関連するコメント移入されません。あなたはコメントを作成すると
{
"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"
}
}
まあ私は気が狂っているよ...うまくいった!そんなにありがとう、@クリダム。私は今、もう少し研究を行うつもり:) – Hinchy
@Hinchy心配しないで、幸せを助ける:) – chridam