[英]Mongoose query condition inside a list
我不確定如何使這個問題的標題更清楚:)
因此,讓我直接跳到架構:
const UserSchema = new Schema({
name: String,
_events: [{ type: Schema.Types.ObjectId, ref: "Event" }]
});
基本上,用戶可以具有由另一個模型Event引用的許多事件。 事件集合如下所示:
const EventSchema = new Schema({
_userId: { type: Schema.Types.ObjectId, ref: "User" },
eventDate: { type: Date, required: true },
instructions: String,
});
我正在對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);
}
});
這很完美。 但是我只想列出將來的事件。 如何修改查詢以執行eventDate
>當前日期的條件?
您應該在填充函數中查詢以下內容:
這里:
.populate({
path: "_events",
model: "Event",
})
添加:
match: { eventDate: { $gte: Date.now() } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.