[英]Mongoose query condition inside a list
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. 基本上,用户可以具有由另一个模型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: 我正在对Mongoose进行查询,该查询列出了用户创建的所有事件,如下所示:
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? 如何修改查询以执行eventDate
>当前日期的条件?
You should query for that in the populate function as follows: 您应该在填充函数中查询以下内容:
Here: 这里:
.populate({
path: "_events",
model: "Event",
})
Add this: 添加:
match: { eventDate: { $gte: Date.now() } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.