首页 > 解决方案 > 列表中的猫鼬查询条件

问题描述

我不知道如何使这个问题的标题更清楚:)

所以让我直接跳到架构:

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> 当前日期的条件?

标签: javascriptnode.jsmongodbmongoose

解决方案


您应该在填充函数中查询它,如下所示:

这里:

.populate({
  path: "_events",
  model: "Event",
})

添加这个:

match: { eventDate: { $gte: Date.now() } }  

推荐阅读