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

168
Vistas
mongoose populate count array field

I want to get objects with populate and field of the array that I want to count.
For Example:

const ChildSchema = new mongoose.Schema({
  name: String,
  age: Number,
  siblings: [{type: ObjectId, ref: 'Child'}],
  toys: [{type: ObjectId, ref: 'Toy'}]
})

and I want to get a populate of the siblings and count of the toys in one object, like this:

const Dan = {
  name: "Dan",
  age: 4,
  siblings: [
    {
      name: "Sally",
      age: 7
    },
    {
      name: "Ben",
      age: 10
    },
    {
      name: "Emily",
      age: 2
    }
  ],
  numOfToys: 11
}

I have this already:

const returnedChild = await ChildModel.findById(BenId)
  .populate('siblings', 'name age')
  .select('name age siblings')
  .lean()

How do I include the count of the toy in the returned object?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Just use virtual schemas:

ChildSchema.virtual('toyCount').get(function () {
    return this.toys.length
});

const returnedChild = await ChildModel.findById(BenId)
  .populate('siblings', 'name age')
  .select('name age siblings')
  .lean()
console.log("Toys -> ", returnedChild.toyCount)
about 4 years ago · Juan Pablo Isaza 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