I need to find my data that matches the particular type. Say, I have an array of objects in my DB, with each object having it's leadType : all or leadType: blacklist. Each object has a different kind of leadType value associated with it.
I want to get the complete data that matches the particular leadType, like leadType: 'radar'.
I tried using the following query but along with the documents it matches, it also returns the empty documents that do not matches the specified projection.
This is what I tried:
exports.leads_by_type = (req, res) => {
const { lead_type } = req.body;
Lead.find({}, { leads: { $elemMatch: { leadType: lead_type }}} )
.then(data => {
if (!data || data.length === 0) {
return res.status(404).json({ message: "No data found" });
}
res.status(200).json({ message: "Data found", data });
})
.catch(err => res.status(500).json({ err }));
};
and it returns me the output as follows:
{
"message": "Data found",
"data": [
{
"_id": "5e83427079f7611bdc1e48a0",
"leads": [
{
"education": {
"school": "happy kids corner",
"graduation": "some school"
},
"currentPosition": {
"title": "Salesforce developer",
"endDate": "currently working",
"employmentType": "full-time",
"industry": "information technology"
},
"location": {
"state": "delhi",
"country": "india"
},
"leadType": "radar",
"name": "Ben",
"mobile": 1524524678,
"_id": "5e83427079f7611bdc1e489e"
}
]
},
{
"_id": "5e84cb4fb59fdd1644e7c226",
"leads": [
{
"education": {
"school": "happy kids corner",
"graduation": "some school"
},
"currentPosition": {
"title": "Salesforce developer",
"endDate": "currently working",
"employmentType": "full-time",
"industry": "information technology"
},
"location": {
"state": "delhi",
"country": "india"
},
"leadType": "radar",
"name": "joey",
"mobile": 1524524678,
"_id": "5e84cb4fb59fdd1644e7c224"
}
]
},
{
"_id": "5e84cb70b59fdd1644e7c229",
"leads": []
},
{
"_id": "5e84cb88b59fdd1644e7c22c",
"leads": []
},
{
"_id": "5e84cbb7b59fdd1644e7c232",
"leads": []
},
{
"_id": "5e84cbd9b59fdd1644e7c235",
"leads": [
{
"education": {
"school": "happy kids corner",
"graduation": "some school"
},
"currentPosition": {
"title": "Salesforce developer",
"endDate": "currently working",
"employmentType": "full-time",
"industry": "information technology"
},
"location": {
"state": "delhi",
"country": "india"
},
"leadType": "radar",
"name": "rhea",
"mobile": 1524524678,
"_id": "5e84cbd9b59fdd1644e7c234"
}
]
}
]
}
Please help me out to fix remove these empty objects from the data output


