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.