Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!