【问题标题】:Mongoose query condition inside a list列表中的猫鼬查询条件
【发布时间】:2018-10-10 15:31:45
【问题描述】:

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

所以让我直接跳到架构:

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

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    您应该在填充函数中查询如下:

    这里:

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

    添加这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-07
      • 1970-01-01
      • 1970-01-01
      • 2020-06-02
      • 2012-02-03
      • 2019-10-18
      • 1970-01-01
      相关资源
      最近更新 更多