I fetch data from an external API which give me two collections. One for football games and one for football competitions. I save this data in MongoDB. When I query a football game I want to know each teams standing in the competition.
These are the models.
Game
{
...,
homeTeam: {
id: 1234
},
awayTeam: {
id: 2345
},
...
}
Competition
{
...
standings: [
{
position: 1,
team: {
id: 1234,
...
},
...
},
{
position: 2,
team: {
id: 2345,
...
},
...
}
]
}
I've tried using aggregation with $lookup but I can't get it to work the way I want.
const game = await Game.aggregate([
{$match: {'competition.id': parseInt(req.params.id)} },
{$lookup: {
from: 'competitions',
localField: 'homeTeam.id',
foreignField: 'standings.team.id',
as: 'homeTeam.position',
}}
]);
What I want to have as a result for each game is this.
{
...,
homeTeam: {
id: 1234,
position: 1
},
awayTeam: {
id: 2345
position: 2
},
...
}