Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add value from another collection in MongoDB

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
    },
    ...
}
like image 207
johanforslund Avatar asked Nov 07 '22 16:11

johanforslund


1 Answers

This can be easily done like this with the help of forEach and an if statement. Everything is explained in the comments. Also, feel free to ask if you have any doubts with the code.

let objectsArr = Object.keys(firstOBJ); // get properties
let answer = []; // a new array for your answer
let childs = Object.keys(secondOBJ); // get the properties of secondOBJ
secondOBJ[childs].forEach((val, i) => { // for every property in secondOBJ
  if (firstOBJ[objectsArr[i]].id == val.team.id) { // we match the id's if they are same then we proceed
    name = objectsArr[i]; // we get the name
    answer.push({ // and we pust with the name
      [name]: {
        id: val.team.id, // along with the corresponding properties
        position: val.position
      }
    })
  }
});

Test snippet for the code above.

let firstOBJ = {
  homeTeam: {
    id: 1234
  },
  awayTeam: {
    id: 2345
  }
}
let secondOBJ = {
  standings: [{
      position: 1,
      team: {
        id: 1234,
      },
    },
    {
      position: 2,
      team: {
        id: 2345
      },
    }
  ]
}
let objectsArr = Object.keys(firstOBJ);
let answer = [];
secondOBJ[Object.keys(secondOBJ)].forEach((val, i) => {
  if (firstOBJ[objectsArr[i]].id == val.team.id)
    answer.push({
      [objectsArr[i]]: {
        id: val.team.id,
        position: val.position
      }
    });
});
console.log(answer)
like image 180
weegee Avatar answered Nov 11 '22 09:11

weegee