填充参考对象,它也是参考对象猫鼬

时间:2021-02-28 00:44:51

标签: node.js mongoose mongoose-populate

我有一个名为 Message 的模式,同样定义:

const messageSchema = new mongoose.Schema({
     name : {type : String}
});

module.exports('Message',messageSchema);

我有另一个名为 Topic 的模式,它使用“消息”作为参考对象。

const topicSchema = new mongoose.Schema({
    topics : { type : mongoose.Schema.Types.ObjectId , ref : 'Message' }
});

module.exports('Topic',topicSchema);

我有一个名为 Thread 的架构,它使用一组“主题”对象引用。

const threadSchema = new mongoose.Schema({
    thread : [{ type : mongoose.Schema.Types.ObjectId , ref : 'Topic' }],
    name : {type : String}
});

module.exports('Thread',threadSchema);

如果我们有“线程”文档,如何访问所有“消息”元素?

我尝试执行以下操作:

Thread.findOne({name : 'Climate'}).populate('thread').populate('topics').exec(function(err,data){})

但是我收到错误,因为 thread 人口有一个数组。请帮助正确取消引用 message 对象。

1 个答案:

答案 0 :(得分:0)

经过进一步调查,我能够解决问题。描述了一种不涉及嵌套 exec 语句的简单解决方案。

const myThread = await Thread.find({name : "Climate"}).populate('thread');
//This populates the 'thread' component of the Thread model, which is essentially an array of 'Topic' elements.

由于我们已将 'thread' 字段填充为数组,所以我们可以遍历该字段的每个成员,使用基本的 'message' 模型填充存在的 'topic' 字段。

const myTopic = myThread.thread;
for(let i = 0; i < myTopic.length ; i++)
{
    myCurrentTopic = myTopic[i];
    var myTopicPopulated = await Topic.find({_id : myCurrentTopic._id}).populate('topic');
    //Do further processing

}

这是一种处理此类情况的简单方法,无需使用 path 代理。