Yangxiao Ou Yangxiao Ou - 1 year ago 125
Node.js Question

mongoose populate nested array with condition for array element

I have an ArticleGroup which contains articles, models look like this

var ArticleGroup = new mongoose.Schema({

var Article = new mongoose.Schema({
rate:Number //user's rate number to this article

now A USER (let's call him JACK) want to perform a query to ArticleGroup, populating articles in this group, selecting the rates filed

usually I do this

.exec((err, articleGroup) => {
if (err) return next(err)

but now I ONLY want JACK's rate
if one article has JACK's rate, just return that article like this

uid:"JACK's uid",
rate:"JACK's rate number"

if one article has no JACK's rate, the article is still populated, but with an empty rates filed like this


Is there any way to do this?

Answer Source

In order to obtain this result you should reconsider your data model with something like this:

ArticleGroup = new mongoose.Schema
    some details here ...

ArticleRate = new mongoose.Schema
    uid: String
    rate: Number

Article = new mongoose.Schema
        type: mongoose.Schema.ObjectId
        ref: 'ArticleGroup'

And perform this kind of query:

.find(group: groupId)
   path: 'rates',
   match: { uid: { $in: { JACK_UID } } },
   select: 'rate'

You could find more helpful informations within the Mongoose documentation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download