skip to Main Content
  • Schema for Event

    const eventSchema = new mongoose.Schema(
      {
        title: { type: String, required: true },
        schedule: { type: Date, required: true },
        organizer: { type: mongoose.Schema.Types.ObjectId, ref: "user", required: true },
      },
      { timestamps: true }
    );
    
  • Schema for Bookings

    
    const bookingSchema = new mongoose.Schema(
      {
        requester: { type: mongoose.Schema.Types.ObjectId, ref: "user", required: true },
        event: { type: mongoose.Schema.Types.ObjectId, ref: "event", required: true },
      },
      { timestamps: true }
    );
    
    

    I want to find all the bookings by organizer id.

I tried the below query but it didn’t work. Can anyone help me?

let bookings = await bookingModel.find({ "event.organizer": organizerId })

2

Answers


  1. Chosen as BEST ANSWER
    db.bookings.aggregate([ 
    {
      $lookup: {
        from: "events",
        localField: "event",
        foreignField: "_id",
        as: "event"
        }
    },
    {
      $match : {"event.organizer": organizerId }
    },
    ])
    

    here is the solution How I solved this. Thank you all


  2. There are basically 3 options here:

    • denormalize the data and store the organizerId in the Bookings documents, so you can query it directly
    • use aggregation to read every Bookings documents, $lookup the corresponding Event documents, and then filter by the organizerId
    • use aggregation to $match Event documents with the organizerId, $lookup the corresponding Bookings documents, then $unwind and $project to return the just the Bookings documents.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search