Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

225
Vistas
How to populate the nested objects in mongoose?

here's the booking schema

const bookingSchema = new mongoose.Schema({
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
    required: true,
  },
  routeId:{
    type: mongoose.Schema.Types.ObjectId,
    ref: "Route",
    required: true,
  }
})

In this table the routeId(route schema) contains the Bus table(referenced).

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,
});

and then finally 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 only bus number and not whole bus data. this is the response I am getting. https://i.stack.imgur.com/S1qyZ.png

this is the query that I applied.

router.get("/bus/myBooking/one/:id", auth, async (req, res) => {
  const _id = req.params.id;
  const myBooking = await Booking.findById({ _id })
    .populate({path: 'routeId', populate: 'Bus'})
    .select(["-_id","-userId","-createdAt","-updatedAt","-__v","-passengers._id","-departureDetails._id","-arrivalDetails._id"]);
  try {
    return !myBooking
      ? res.status(404).send("No booking found")
      : res.status(200).send(myBooking);
  } catch (e) {
    res.status(500).send();
  }
});
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

This method works on some versions of mongoose, So you can try this:

 await Booking.findById({ _id })
  .populate({ 
   path: 'routeId',
      populate: {
         path: 'Bus',
         model: Bus,
         select:"-_id busNumber"
   } 
 })
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda