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

132
Views
Mongoose Get only size of a array

I'm using Mongoose and a MongoDB. I have three schemas user and genres and songs.

const userSchema = new Schema({
  name: String,
  age: String,
  favorite_genres: {
    type: Schema.Types.ObjectId,
    ref: 'Genre'
  }
});

const genreSchema = new Schema({
  name: String,
  songs: {
    type: Schema.Types.ObjectId,
    ref: 'Song'
  }
});

const songSchema = new Schema({
  title: String,
  artist: String,
  length: String,
  year: String
});

those are simplifid schemas, but they will do for this puprose. So when I query a user I want to populate the doc with the favorite genres. But there (due to the potential amount of data) not with the ids of all songs, but only the number of songs. How can I achieve that?

I tried virtuals but they don't work the way I wanted it. What I'm looking for is sth like the following:

const user = await User.findById(userID).populate({path: 'favorite_genres', select: 'name', sizeof: 'songs'}).lean()

// or

const user = await User.findById(userID).populate({path: 'favorite_genres', select: ['name', 'songs.length']}).lean()

Does anyone have an idea?

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

Look at the link I attached. It's a similar question, I think You will find Your answer over there. You can find Your answer here

about 4 years ago · Santiago Gelvez 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!