这个问题已被要求在这里死亡,但似乎并没有明确的答案。
所以我有一个数据库,其中一个用户有很多主题,帖子&评论,A主题有很多帖子,帖子有很多评论。
添加用户,主题,帖子&评论工作正常。主题也在显示时填充其中的帖子。(带有轻微的重定向故障)。但我无法在帖子中填写评论。这就是我到目前为止所拥有的。
主题控制器内的Gettopic方法
gettopic: function(req, res){
console.log("get_topic query", req.body._id)
Topic.findOne({_id: req.body._id}).populate('posts').populate('posts.comments').exec(function (err, topic) {
if(err){
console.log("Something went Wrong");
res.json(err)
}else{
console.log(topic);
res.json(topic);
}
})
}
主题模型
var TopicSchema = new mongoose.Schema({
topic: String,
description: String,
category: String,
post_count: Number,
user_name: String,
_User: {type: Schema.Types.ObjectId, ref: 'User'},
posts: [{type: Schema.Types.ObjectId, ref: 'Post'}],
created_at: Date
});
发布模型
var PostSchema = new mongoose.Schema({
post: String,
up_vote: Number,
down_vote: Number,
user_name: String,
_User: {type: Schema.Types.ObjectId, ref: 'User'},
_Topic: {type: Schema.Types.ObjectId, ref: 'Topic'},
comments: [{type: Schema.Types.ObjectId, ref: 'Comment'}],
created_at: Date
});
评论模型
var CommentSchema = new mongoose.Schema({
comment: String,
user_name: String,
_User: {type: Schema.Types.ObjectId, ref: 'User'},
_Post: {type: Schema.Types.ObjectId, ref: 'Post'},
created_at: Date
});
查找Topic.findOne正在正常工作,甚至填充“帖子”,但在填充评论时,只有Ids显示,在后端和前端都有console.log。
正如您所看到的那样,它没有完全填充数组,只能在终端中将其视为[OBJECT],在JS Console中只能将其视为Id。
我做错了什么?
的console.log(JSON.stringify(topic.posts,未定义,2))
{
"_id": "56b3f865fe0aca747e9dae4f",
"topic": "New topic in new DB",
"description": "Testing Phase 1",
"category": "HTML",
"user_name": "Ani",
"post_count": 0,
"__v": 7,
"posts": [
{
"_id": "56b3f880fe0aca747e9dae50",
"post": "Posting Answer Phase 1",
"user_name": "Ani",
"up_vote": 0,
"down_vote": 0,
"created_at": "2016-02-05T01:18:56.709Z",
"__v": 3,
"comments": [
"56b40368004a0707806e4b93",
"56b4046beef00e4c82126269",
"56b406656171e44383374cf0"
]
},
{
"_id": "56b4061a51c0d3f282b89a95",
"post": "Answer/Post V.2.0",
"user_name": "Ani",
"up_vote": 0,
"down_vote": 0,
"created_at": "2016-02-05T02:16:58.575Z",
"__v": 1,
"comments": [
"56b4062551c0d3f282b89a96"
]
}
的console.log(JSON.stringify(主题,未定义,2))
"posts": [
{
"_id": "56b3f880fe0aca747e9dae50",
"post": "Posting Answer Phase 1",
"user_name": "Ani",
"up_vote": 0,
"down_vote": 0,
"created_at": "2016-02-05T01:18:56.709Z",
"__v": 3,
"comments": [
"56b40368004a0707806e4b93",
"56b4046beef00e4c82126269",
"56b406656171e44383374cf0"
]
},
{
"_id": "56b4061a51c0d3f282b89a95",
"post": "Answer/Post V.2.0",
"user_name": "Ani",
"up_vote": 0,
"down_vote": 0,
"created_at": "2016-02-05T02:16:58.575Z",
"__v": 1,
"comments": [
"56b4062551c0d3f282b89a96"
]
}
答案 0 :(得分:0)
您可以尝试使用mongoose-deep-populate插件来嵌套深层对象
var deepPopulate = require('mongoose-deep-populate');
Topic.findOne({
_id: req.body._id
}).deepPopulate('posts posts.comments').exec(function (err, topic) {
if (err)
res.json(err)
else{
console.log(topic);
res.json(topic);
};
});