从MongoDB中的另一个集合中增加价值

时间:2019-06-23 16:27:36

标签: javascript mongodb mongoose

我从外部API获取数据,这给了我两个集合。一种用于足球比赛,另一种用于足球比赛。我将此数据保存在MongoDB中。当我查询足球比赛时,我想知道参加比赛的每支球队。

这些是模型。

游戏

{
    ...,
    homeTeam: {
        id: 1234
    },
    awayTeam: {
        id: 2345
    },
    ...
}

竞争

{
    ...
    standings: [
    {
        position: 1,
        team: {
            id: 1234,
            ...
        },
        ...
    },
    {
        position: 2,
        team: {
            id: 2345,
            ...
        },
        ...
    }
    ]
}

我尝试将聚合与$ lookup结合使用,但无法使其按我想要的方式工作。

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',
        }}
    ]);

我希望每场比赛的结果是这个。

{
    ...,
    homeTeam: {
        id: 1234,
        position: 1
    },
    awayTeam: {
        id: 2345
        position: 2
    },
    ...
}

1 个答案:

答案 0 :(得分:1)

在forEach和if语句的帮助下,可以很容易地做到这一点。注释中说明了所有内容。另外,请随时询问您对代码是否有疑问。

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
      }
    })
  }
});

上面的代码的测试代码段。

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)