简体   繁体   中英

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. 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:

  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?

You should query for that in the populate function as follows:

Here:

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

Add this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM