I'm having an issue populating a nested array of documents with Mongoose and none of the solutions I've seen in other threads seem to work.
Here are the models relevant to my issue:
Match
const MatchSchema = new Schema({
home: {
type: Schema.Types.ObjectId,
ref: 'Team',
},
away: {
type: Schema.Types.ObjectId,
ref: 'Team',
},
competition: {
type: Schema.Types.ObjectId,
ref: 'Competition',
},
date: Date,
live: Boolean,
odds: [
{
type: Schema.Types.ObjectId,
ref: 'Odd',
}
],
})
Odd
const OddSchema = new Schema({
oddValue: Number,
option: {
type: Schema.Types.ObjectId,
ref: 'Option'
},
website: {
type: Schema.Types.ObjectId,
ref: 'Website'
},
market: {
type: Schema.Types.ObjectId,
ref: 'Market'
},
match: {
type: Schema.Types.ObjectId,
ref: 'Match'
},
})
Market
const MarketSchema = new Schema({
market: String,
period: String,
options: [
{
option: {
type: Schema.Types.ObjectId,
ref: 'Option'
},
}
],
})
Option
const OptionSchema = new Schema({
name: String,
})
Here's how I'm currently populating the documents
let matches = await Match.find()
.populate('home')
.populate('away')
.populate({
path: 'competition',
populate: [
{ path: 'country', model: 'Country' },
{ path: 'sport', model: 'Sport'}
]
})
.populate({
path: 'odds',
populate: [
{ path: 'option', model: 'Option' },
{ path: 'website', model: 'Website' },
{ path: 'market', model: 'Market' }
]
})
I'm having issues populating the nested 'options' field in the populated market document.
I've tried chaining populate calls, like
.populate({
path: 'odds',
populate: {
{ path: 'market', model: 'Market',
populate: { path:'options.option', model: 'Option' }}
}
})
but I keep getting the same output of the Odd documents, where all fields are successfully populated except the options array in the nested market field.
Is there something wrong with the way I'm organising data? Am I calling populate incorrectly? Thanks in advance
The options field in the Market model was not defined correctly. Should be
const MarketSchema = new Schema({
market: String,
period: String,
options: [
{
type: Schema.Types.ObjectId,
ref: 'Option'
}
],
})