2017-04-09 62 views
2

我正在创建一个blogapp。两个模型评论和USERPROFILE,评论看起来是这样的:猫鼬如何填充模型中引用的数组

var commentSchema = new Schema({ 
      userId: {type: Schema.Types.ObjectId, ref: 'userProfile'}, 
      replyCommentId: [{type: Schema.Types.ObjectId, ref:'Comment'}], 
      commentDesc: String, 
      date: {type: String, default: Date.now()} 
      }); 

我已保存的回覆意见本身并参考通过存储阵列replycomment ID主要的意见。

我试图填充这些回复字段。

commentsModel.findOne({_id: commentId}).populate('replyCommentId') 
.populate('replyCommentId.userProfile').exec(function (err, docs) { 
    cb(err, docs); 
}) 

我可以填充replyCommentId与模型,但内replycommentIduserProfile是没有得到填充。

回答

0

你可以尝试这样的:

... 
 

 
const populateQuery = []; 
 
populateQuery.push({ 
 
    path: 'replyCommentId' 
 
}, { 
 
    path: 'replyCommentId', 
 
    populate: { 
 
    path: "userProfile", 
 
    model: "Comment", 
 
    }, 
 
}); 
 

 
fields.commentsModel.findById(commentId) 
 
    .populate(populateQuery) 
 
    .exec((error, docs) => { 
 
    cb(error, docs); 
 
    }); 
 

 
....

+0

它为我工作。我有你的逻辑。谢谢。我可以给你upvote,但我是堆栈溢出的新手,我正在建立我的声望。 –

+0

那么如果你接受我的答案,你会得到2的声望;) –

0

你不需要使用两个填入quesries填充replyCommentId和用户id内部的。它可以使用一个填充来完成。

你可以简单地尝试这个办法:

commentsModel 
    .findOne({_id: commentId}). 
    .populate({ 
     path : 'replyCommentId', 
     populate : { 
      path :'userId' 
     } 
    }).exec(function (err, docs) { 
     cb(err, docs); 
    }); 

有关猫鼬填充及其选项的详细信息,请参阅Mongoose Populate Documentation。查找填充多个级别

+0

我已经尝试过,它不起作用userId没有得到与模型填充,它仍然被引用。 –

+0

你可以试试我编辑的答案。这将为你工作 –