Mongoose - search a new collection based on the first collection result

I have two collections as follows :

This is my vehicle schema

  const VehicleSchema = new schema({
  user: {
    type: schema.Types.ObjectId,
    ref: "users"
  },
  name: {
    type: String,
    required: true
  },
  brand: {
    type: String,
    required: true
  },
  plate: {
    type: String,
    required: true
  },
  IMEI: {
    type: String,
    required: true
  }
});

This is my Trip schema

const TripSchema = new schema({
  date: {
    type: Date,
    default: Date.now
  },
  IMEI: String,
  data: [
    {
      lat: String,
      lon: String
    }
  ]
});

Trip and Vehicle schemas share the the key IMEI, so when the user is logged in I wanna grab the trips based on the IMEI number, what is the most efficient way to approach this problem ? here is a look at my router

router.get(
  "/",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    Vehicles.find({ user: req.user.id }).then(vehicles => {
      if (!vehicles) {
        return res.json({ error: "you do not have any vehicles yet" });
      }
      Trips.find().then(trips => {
        // ??
      });
    });
  }
);

1 answer

  • answered 2018-10-09 16:30 Akrion

    You can simply do a $lookup and do a left join on trips with vehicles:

    db.vechicles.aggregate([
       {
         $lookup:
           {
             from: "trips",
             localField: "IMEI",
             foreignField: "IMEI",
             as: "trips"
           }
      }
    ])
    

    This should get you what you want in one call.

    Note this is available in mongodb versions 3.2+