'How to filter while populating in mongoose?
I want to filter results based on populated data in mongoose. How to do that?
Consider date = 2022-05-22T00:00:00.000Z
Tried code:
const attendances = await Attendance.find({ active: { $in: id } }).populate(
{
path: "meeting",
model: Meeting,
match: { date: { $lt: today } },
select: "title date",
}
);
Results:
{
_id: new ObjectId("6283fb550079acdda0cd9027"),
meeting: {
_id: new ObjectId("6283fb550079acdda0cd9024"),
title: 'aaa',
date: 2022-05-19T00:00:00.000Z
}
},
{ _id: new ObjectId("628579e3aa11102f928d6f1a"), meeting: null }
I want to remove the second object based on the time compared to populated data.
Solution 1:[1]
you can use aggregation to filter
const attendances = await Attendance.aggregate([
{
$match: {//match anything you want like normal query}
},
{
$lookup : {
from: 'meetings' //Collection's name,
localField: 'meeting', //field you want to use to lookup
foreignField: '_id',
as: 'meeting',
}
},
{
$unwind :{
path: '$meeting',
preserveNullAndEmptyArrays: true,
},
},
{
$match : {
meeting : {$ne : null} //filter meeting !== null or you can filter anything you want in meeting like bellow
"meeting.date" : {$lt : //Date}
}
}
])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | luong vy |
