Reputation: 91
I have tried using mongo db aggregation pipeline with the elemMatch operator but it doesn't output the result that i need, but if i use the same conditions inside a find() it works perfectly. plz help me with this issue
working version when using find()
Bookings.find(
{
sessionDates: { $elemMatch: { $gte: startDate, $lt: endDate } },
tourId: tourId,
sessionStatus: "PENDING"
}
)
not working when using with aggregation
Bookings.aggregate(
[
{
$match: {
sessionDates: { $elemMatch: { $gte: startDate, $lt: endDate } },
tourId: tourId,
sessionStatus: "PENDING"
}
}
]
);
here is a sample of the data I am using
{
"sessionDates": [
"2022-05-16T00:00:00.000Z",
"2022-05-17T00:00:00.000Z",
"2022-05-18T00:00:00.000Z"
],
"_id": "6228592690b8903618a95280",
"tourId": "62270fb22e7c5942d010b151",
"sessionStatus": "PENDING",
"createdAt": "2022-03-09T07:37:10.237Z",
"updatedAt": "2022-03-09T07:38:24.003Z",
"__v": 0
}
Upvotes: 0
Views: 332
Reputation: 12964
Mongoose does not cast aggregation pipeline stages (1), (2) and you have to do it manually and make sure the values have the correct type, in your example you must cast tourId
to an ObjectId
using mongoose.Types.ObjectId
and the same thing for startDate
and endDate
if sessionDates
values type is Date
and not String
:
Bookings.aggregate(
[
{
$match: {
sessionDates: { $elemMatch: { $gte: startDate, $lt: endDate } },
// If sessionDates values type is `Date`
// sessionDates: { $elemMatch: { $gte: new Date(startDate), $lt: new Date(endDate) } },
tourId: new mongoose.Types.ObjectId(tourId),
sessionStatus: "PENDING"
}
}
]
);
Upvotes: 1