node.js - Mongoose : query on a field on an array of ref documents, -


this question has answer here:

here models:

var locationschema = new schema( {     events: [         {             type: mongoose.schema.types.objectid,             ref: 'event'         }     ] }) var eventschema = new schema( {     title  : string,      location: {         type: mongoose.schema.types.objectid,         ref: 'location'     } }) 

i query location model field inside event model.

the following 1 doesn't work

findone({events: {$elemmatch: {title: 'test'}}}) 

i'm not sure that's possible make ...

when use references can use population run "sub query" on referenced documents select ones should included.

location.find({ ... }).populate({   path  : 'events',   match : { title : 'test' } }).exec(...); 

which way around (query location , populate event, or other way around) depends on exact query need run. it's performant run "main" query on model yield least results.

this method still return documents matched main query, , have perform postprocessing filter documents don't have matched event references.


Comments