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 ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With