I have a dynamic model 'Dialog' model in which a field called lecture is sometimes available sometimes not, and the Lecture model is defined on different nodejs server. I want to populate the result of the lecture in the dialog as well. so I try using populate but it gives a Schema not register error. So I am trying to using $lookup to join data from different collections. But, the Aggregate method returns an array and I need an object. I have tried accessing using arr[0] using index zero. But I have a method defined on the Dialog model. when I try accessing it throws an error.
const resp = await DialogModel.aggregate([
{
$match: {
$and: query
}
},
{
$lookup: {
from: "lectures",
localField: "lecture",
foreignField: "_id",
as: "lectureDetail"
}
},
{
$unwind: {
path: "$lectureDetail",
preserveNullAndEmptyArrays: true
}
}
]);
Here is current out:
[
{
_id: 60ab86e1671c602015741955,
lecture: 607d4d3de9b8be1f29e56e94,
lectureDetail: {
_id: 607d4d3de9b8be1f29e56e94,
course: 6076ba3a01060327b3231a3c,
owner: 607434cd63b75949f61cc065,
name: 'Lecture 11',
startDate: 2021-05-24T07:00:00.000Z,
endDate: 2021-05-24T08:00:00.000Z
}
}
]
Here is the expected output:
{
_id: 60ab86e1671c602015741955,
lecture: 607d4d3de9b8be1f29e56e94,
lectureDetail: {
_id: 607d4d3de9b8be1f29e56e94,
course: 6076ba3a01060327b3231a3c,
owner: 607434cd63b75949f61cc065,
name: 'Lecture 11',
startDate: 2021-05-24T07:00:00.000Z,
endDate: 2021-05-24T08:00:00.000Z
}
}
If I try getting access using the index, and call method on it. method Defined on my Model through an error of is not a function.
Here is my query. Kindly guide me on how to solve this issue.
lectureDetailis an object, you can directly access it.. and when you show us, please remove unnecessary fields for better eye sight