Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose : query on a field on an array of ref documents, [duplicate]

here are my 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 would like to query from the Location model a field inside the Event model.

The following one doesn't work

findOne({events: {$elemMatch: {title: 'test'}}})

I'm not sure even that's possible to make it ...

like image 330
GuillaumeC Avatar asked Jul 15 '15 09:07

GuillaumeC


1 Answers

When you use references you can use population to run a "sub query" on referenced documents to select which ones should be included.

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

Which way around (query Location and populate Event, or the other way around) depends on the exact query you need to run. It's most performant to run the "main" query on the model that will yield the least results.

This method will still return all documents that matched the main query, and you have to perform some postprocessing to filter the documents that don't have any matched event references.

like image 148
robertklep Avatar answered Oct 03 '22 01:10

robertklep