Search code examples
node.jsmongodbexpressmongoosemongoose-populate

How to populate data from another collections in mongoose?


I want to populate the busNumber from bus Bus table to the trip table. Here's the bus model

const busSchema = new mongoose.Schema(
  {
    busNumber: {
      type: String,
      unique: true,
      required: true,
    },
    seats: {
      type: Number,
    },
  },
  {
    timestamps: true,
  }
);

now I want to show the bus number inside the trip table instead of bus._id. I know how to exclude data but don't know how to include data from other collections. here's the route model where I included the bus model

const routeSchema = new mongoose.Schema({
  location:{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Location',
    required: true
  },
  duration: {
    type: Number,
    required: true,
  },
  Bus:{
    type: mongoose.Schema.Types.ObjectId,
    ref:"Bus",
    required: true
  },
  date: {
    type:String,
    required: true
  },
},
{
  timestamps: true,
});

here's the query:

router.get("/trips", async (req, res) => {
  if ((!req.query.departure && !req.query.arrival) || !req.query.date) {
    return res.send({
      error: "Please enter the data to get the trip",
    });
  }
  const { departure, arrival, date } = req.query;

  const locations = await Location.find({
    "departureLocation.name": departure,
    "arrivalLocation.name": arrival,
  });

  const ids = locations.map(location => location._id);
  const routes = await Route.find({
    $and: [{ location: { $in: ids } }, { date }],
  }).select(['-busId', '-location', '-_id', '-createdAt', '-updatedAt', '-__v']);

  return !routes ? res.status(404).send() : res.status(200).send(routes);
});

Here's the result I am getting https://i.sstatic.net/AwK5N.png

How to use the populate() function to get data from another collection in mongoose


Solution

  • use this code for your populate Bus key

     router.get("/trips", async (req, res) => {
          if ((!req.query.departure && !req.query.arrival) || !req.query.date) {
            return res.send({
              error: "Please enter the data to get the trip",
            });
          }
          const { departure, arrival, date } = req.query;
        
          const locations = await Location.find({
            "departureLocation.name": departure,
            "arrivalLocation.name": arrival,
          });
        
          const ids = locations.map(location => location._id);
          const routes = await Route.find({
            $and: [{ location: { $in: ids } }, { date }],
          }).populate("Bus").select(['-busId', '-location', '-_id', '-createdAt', '-updatedAt', '-__v']);
        
          return !routes ? res.status(404).send() : res.status(200).send(routes);
        });