I have a schema called Message, defined likewise:
const messageSchema = new mongoose.Schema({
name : {type : String}
});
module.exports('Message',messageSchema);
I have another schema called Topic, which uses 'Message' as a reference object.
const topicSchema = new mongoose.Schema({
topics : { type : mongoose.Schema.Types.ObjectId , ref : 'Message' }
});
module.exports('Topic',topicSchema);
I have a schema called Thread, which uses an array of 'Topic' object references.
const threadSchema = new mongoose.Schema({
thread : [{ type : mongoose.Schema.Types.ObjectId , ref : 'Topic' }],
name : {type : String}
});
module.exports('Thread',threadSchema);
How to access all the 'Message' elements if we have a 'Thread' document with us?
I tried doing the following:
Thread.findOne({name : 'Climate'}).populate('thread').populate('topics').exec(function(err,data){})
but I am getting errors since thread population has an array. Please help in correctly dereferencing the message object.
After further investigations, I was able to solve the problem. An easy solution not involving nested exec
statements is described.
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.
Since we have populated the 'thread' field as an array, we can iterate through each member of that field, populating the 'topic' field present with the base 'message' model.
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
}
This is a simple way to handle such cases, without resorting to usage of the path
proxy.