首页 > 解决方案 > 从 MongoDB 中的另一个集合中添加值

问题描述

我从给我两个集合的外部 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
    },
    ...
}

标签: javascriptmongodbmongoose

解决方案


这可以在 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)


推荐阅读