I am a beginner in MongoDB and am working on my personal project. I am trying to populate employees field for teamSurveyForms, but it is returning Array(0) for teamSurveyForm.employees.Can anyone tell what I am doing wrong?
const pipeline = [
{
$lookup: {
from: 'departments',
localField: 'department',
foreignField: '_id',
as: 'departmentData',
},
},
{
$lookup: {
from: 'forms',
localField: 'forms',
foreignField: '_id',
as: 'formsData',
},
},
{
$lookup:{
from: 'employees',
localField: 'teamSurveyForms.employees',
foreignField: '_id',
as: 'teamFormEmployees',
},
},
{
$unwind: {
path: '$departmentData',
preserveNullAndEmptyArrays: true,
},
},
{
$project: {
fName: 1,
lName: 1,
empCode: 1,
email: 1,
password:1,
empType: 1,
designation: 1,
DOJ:1,
department: '$departmentData.name',
selfSurveyForms: {$cond:
{
if:employeeWithForm,
then:{
$map:{
input:{
$filter:{
input:'$formsData',
as:'selfForm',
cond:{$eq:['$$selfForm.FType','Self']}
}
},
as:'selfForm',
in:{
_id:'$$selfForm._id',
FType:'$$selfForm.FType',
title:'$$selfForm.title',
description:'$$selfForm.description',
department: '$departmentData.name',
employees:[],
}
},
},
else:null
}
},
teamSurveyForms: {$cond:
{
if:employeeWithForm,
then:{
$map: {
input: {
$filter:{
input:'$formsData',
as:'teamForm',
cond:{$eq:['$$teamForm.FType','Team']}
}
},
as:'teamForm',
in:{
_id:'$$teamForm._id',
FType:'$$teamForm.FType',
title:'$$teamForm.title',
description:'$$teamForm.description',
department: '$departmentData.department',
employees:{
$map: {
input: '$teamFormEmployees',
as: 'employee',
in: {
_id:'$$employee._id',
name: {$concat: ['$$employee.fName', ' ', '$$employee.lName']},
}
},
},
}
}
},
else:null
}
},
},
},
{
$match: findQueryData, // Apply the conditions for searching
},
{
$skip: (page - 1) * items_per_page, // Skip records based on page number
},
{
$limit: Number(items_per_page), // Limit the number of records per page
},
];
data=await FormModel.aggregate(pipeline);
I want to get data with all fields like fName,lName,empCode,email,password,empType,designation, DOJ, department and forms split into selfSurveyForms and teamSurveyForms and in both forms I need FType, title, description, department and employees. In selfSurveyForms, I am sending employees as empty array but in teamSurveyForms I need employees (which is an array of ids of employee) by populating it with employee collection.
selfSurveyForms and teamSurveyForms both are array.