Reputation: 3815
I am not sure how to make the title of this question a bit more clear :)
So let me jump directly to the schema:
const UserSchema = new Schema({
name: String,
_events: [{ type: Schema.Types.ObjectId, ref: "Event" }]
});
Basically a user can have a number of events that are referenced by another model, Event. The event collection looks like this:
const EventSchema = new Schema({
_userId: { type: Schema.Types.ObjectId, ref: "User" },
eventDate: { type: Date, required: true },
instructions: String,
});
I am doing a query on Mongoose that lists all the events created by the user, as follows:
app.get("/api/events/", requireAuth, async (req, res, next) => {
try {
const userEvents = await User.findById(req.user._id)
.populate({
path: "_events",
model: "Event",
})
.select({ _events: 1 })
.exec();
res.send(userEvents);
} catch (err) {
next(err);
}
});
This works perfectly. However I am interested in listing only future events. How can I modify the query to do a condition where eventDate
> current date?
Upvotes: 1
Views: 302
Reputation: 3475
You should query for that in the populate function as follows:
Here:
.populate({
path: "_events",
model: "Event",
})
Add this:
match: { eventDate: { $gte: Date.now() } }
Upvotes: 2