gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:14:40 26 4
gpt4 key购买 nike

我从提供两个集合的外部 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)

关于javascript - 从 MongoDB 中的另一个集合中添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56725810/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com