javascript - 从 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
},
...
}
解决方案
这可以在 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)
推荐阅读
- python - Python:如果分隔符不可用,则使用 str.split 拆分字符串
- tensorflow - 如何使用 TensorRT 优化您的 TensorFlow 模型?
- android - ViewPager2 滑动在 RecyclerView 中不起作用
- mysql - 等效查询对不同的表抛出错误:语法错误或访问冲突:1055 SELECT 列表的表达式 #2 不在 GROUP BY 中
- flutter - 决定在 Dart/Flutter 中添加 const 的对象层次结构中的哪个级别
- functional-programming - Ocaml 中的表达式
- java - Dagger2 Android 依赖注入 java
- python - Python 函数以最小的可能时间顺序 (O(n)) 在字典中查找所有第二低的 SCORERS
- javascript - 在文本中查找大写字母的问题
- r - R中的子集字符向量