I would like to get all Notifications between a start and end date that are related to a Register when I pass in a userId.
Your solution looks almost right, provided that dateStart
and dateStart
are actually Date
objects and not String
s.
Your Try 2 was incomplete I'm not sure it uses the $lookup
from Try 1 or not. If so you have to make sure the output of $lookup
is the same as input of $filter
. So you should change as
in $lookup
to match input
of $filter
{
$lookup: {
from: "notifications",
localField: "accessToken",
foreignField: "accessToken",
as: "items" // here
}
}
Alternative Solution
I'm not sure what you want as output. If you only need array of notifications without the user object, you can try the following.
[{
$match: { userId: mongoose.Types.ObjectId(userId) }
}, {
$lookup: {
from: "notifications",
localField: "accessToken", // don't forget to index register.accessToken
foreignField: "accessToken", // don't forget to index notification.accessToken
as: "notifications"
}
}, {
$unwind: "$notifications"
}, {
$match: {
dateCreated: { $gte: dateStart, $lte: dateEnd } // dateStart, dateEnd should be Date objects
}
}, { // optional, move notifications to top lvel
$replaceRoot: { root: '$notifications' }
}]