Search code examples
node.jsmongodbreferencemongoosesubdocument

Mongoose find in array of referenced subdocuments


I am trying to find certain visits coming from an ip.The visits schema looks like this :

var VisitSchema = new Schema({
visitId:        String,
ip:             [{ type: Schema.Types.ObjectId, ref: 'VisitorIp' }]
});
mongoose.model('Visit', VisitSchema);

the ip schema looks like this :

var VisitorIpSchema = new Schema({
ip:             String,
country:        String
});
mongoose.model('VisitorIp', VisitorIpSchema);

when i try to run the normal find for a specific ip :

Visit.find({ip.ip:myIp}))
.populate('ip')
.exec(function(err, visits){
  console.log(visits)
})

it returns an empty array. All the recordings in the mongo database look and behave normally.

Please help I have run out of ideas.


Solution

  • One not-so-elegant approach that you can take is to query after populating, i.e. get all the visits, populate the visits' ip documents with a query filter and when the query executes you'll then need to manually filter out visit documents that don't have any IP docs that matched the populate criteria, something like:

    Visit.find({})
        .populate('ip', null, { "ip": myIp } )
        .where('ip.ip').equals(myIp) /* where('ip.ip').in([myIp]) */
        .exec(function(err, visits){
            visits = visits.filter(function(doc){
                return visits.ip.length;
            })
            // do stuff with visits
        });