从 MongoDB 中的另一个集合添加值

joh*_*und 5 javascript mongoose mongodb

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

这些是模型。

游戏

{
    ...,
    homeTeam: {
        id: 1234
    },
    awayTeam: {
        id: 2345
    },
    ...
}
Run Code Online (Sandbox Code Playgroud)

竞赛

{
    ...
    standings: [
    {
        position: 1,
        team: {
            id: 1234,
            ...
        },
        ...
    },
    {
        position: 2,
        team: {
            id: 2345,
            ...
        },
        ...
    }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我试过将聚合与 $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',
        }}
    ]);
Run Code Online (Sandbox Code Playgroud)

我希望每场比赛都有这样的结果。

{
    ...,
    homeTeam: {
        id: 1234,
        position: 1
    },
    awayTeam: {
        id: 2345
        position: 2
    },
    ...
}
Run Code Online (Sandbox Code Playgroud)

wee*_*gee 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
      }
    })
  }
});
Run Code Online (Sandbox Code Playgroud)

上面代码的测试片段。

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
      }
    })
  }
});
Run Code Online (Sandbox Code Playgroud)