Quiero obtener objetos con población y campo de la matriz que quiero contar.
Por ejemplo:
const ChildSchema = new mongoose.Schema({ name: String, age: Number, siblings: [{type: ObjectId, ref: 'Child'}], toys: [{type: ObjectId, ref: 'Toy'}] })y quiero obtener una población de los hermanos y contar los juguetes en un objeto, así:
const Dan = { name: "Dan", age: 4, siblings: [ { name: "Sally", age: 7 }, { name: "Ben", age: 10 }, { name: "Emily", age: 2 } ], numOfToys: 11 }Ya tengo esto:
const returnedChild = await ChildModel.findById(BenId) .populate('siblings', 'name age') .select('name age siblings') .lean()¿Cómo incluyo el recuento del juguete en el objeto devuelto?
Solo usa esquemas virtuales:
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)