javascript - 列表中的猫鼬查询条件
问题描述
我不知道如何使这个问题的标题更清楚:)
所以让我直接跳到架构:
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() } }
推荐阅读
- interpolation - 图像缩小如何与最近邻插值一起使用?
- node.js - 为什么我在安装节点 js 时收到此错误
- android - 如何在 android 中对 Patterns.PHONE 进行单元测试
- mongodb - 按列表中的元素和按字段计数
- itext7 - iText7 - PdfReader 构造函数锁定非 pdf 文件
- python - Python binance client.create_test_order 什么都不返回,没有错误
- database - 在单个实体下创建多个关系(数据库设计)
- javascript - 无法在移动设备上选择 IOS 和 Android 上的文件
- angular - 为什么本地构建和 Azure CI/CD 管道的 vendor.js 文件大小不同?
- javascript - 使用 jQuery 更新表格,但浏览器不刷新页面