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?
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)