Sam Axe
Sam Axe

Reputation: 545

Mongoose query parent and include children with reference

I have 2 Mongoose Schemas. Location and Place. I need to be able to pull location information when I query place and it works well with populate. However in another case, I need to find all places that belong to location.

Does this mean that I need to reference Places in Location Schema as well? Multiple places can belong to single location. I can't embed places in location because places will have sub information, and I don't want locations document get too big cause of that.

var LocationSchema = new mongoose.Schema({
  name: {
    type: String,
  },
}); 

var PlaceSchema = new mongoose.Schema({
  location: {type: mongoose.Schema.Types.ObjectId, ref: 'Location'},
  type: String,
});  

Upvotes: 1

Views: 2167

Answers (1)

Jim B.
Jim B.

Reputation: 4714

You just need to query by the location id.

Places.find({location: { $in: [location ids] }}).then(places => {...})

Upvotes: 1

Related Questions