0

The Mongoose collection Question has a subdoc field labelled answers: []. I want to run a query that returns relevant Question fields and the count of the answers.

My current query is:

Question.find()
  .sort({ createdAt: 'desc' })
  .limit(30)
  .select({
    title: 1,
    owner: 1,
    createdAt: 1,
  })
  .populate('owner', 'username')
  .lean()
  .exec((err, questions) => { ... });

I want to do something like this:

Question.find()
  .sort({ createdAt: 'desc' })
  .limit(30)
  .select({
    title: 1,
    owner: 1,
    createdAt: 1,
    answerCount: answers.length, // give me number of subdocs
  })
  .populate('owner', 'username')
  .lean()
  .exec((err, questions) => { ... });

Is there a way to get the count of the subdocs without returning the full subdoc array (they are large) and without running a second query?

Not a duplicate of this question asking how to count the number of items in an array as I don't want to return the subdocs entirely.

Jacob
  • 1,560
  • 4
  • 19
  • 41
  • 1
    Why don't you populate `_id` field of answers and count them? `.populate('answers', '_id')` – Medet Tleukabiluly Nov 05 '17 at 01:12
  • Found an answer after following @MedetTleukabiluly and [this answer from another question](https://stackoverflow.com/a/25965933). I would answer but... – Jacob Nov 05 '17 at 01:33

0 Answers0