【问题标题】:mongoose how to populate an array referenced within the model猫鼬如何填充模型中引用的数组
【发布时间】:2017-04-13 15:09:08
【问题描述】:

我正在制作一个博客应用程序。两个model的comment和userProfile,comment看起来是这样的:

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()}
          });

我已将回复保存为 cmets 本身,并通过存储在数组中的回复评论 ID 引用主评论。

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

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

我可以用模型填充replyCommentId,但replycommentId 中的userProfile 没有被填充。

【问题讨论】:

    标签: mongoose


    【解决方案1】:

    你可以这样试试:

    ...
    
    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);
      });
    
    ....

    【讨论】:

    • 它对我有用。我明白了你的逻辑。谢谢你。我可以给你投票,但我是堆栈溢出的新手,我正在建立自己的声誉。
    • 好吧,如果您接受我的回答,您将获得 2 声望 ;)
    【解决方案2】:

    您不需要使用两个填充查询来填充其中的replyCommentId 和userId。可以使用一个填充来完成。

    你可以试试这个:

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

    有关 Mongoose Populate 及其选项的更多信息,请参阅Mongoose Populate Documentation。寻找跨多个级别填充

    【讨论】:

    • 我试过了,它不起作用 userId 没有被模型填充,它仍然被引用。
    • 你可以试试我编辑的答案。这对你有用
    猜你喜欢
    • 1970-01-01
    • 2021-06-29
    • 2019-02-24
    • 2014-04-19
    • 1970-01-01
    • 2015-07-13
    • 2021-05-16
    • 2016-04-25
    • 2020-11-08
    相关资源
    最近更新 更多