gpt4 book ai didi

node.js - MongoDB 插入嵌套数组

转载 作者:太空宇宙 更新时间:2023-11-03 21:50:32 25 4
gpt4 key购买 nike

我有这个方案

{
"_id": {
"$oid": "5e187b1791c51b4b105fcff0"
},
"username": "test",
"email": "test@test.com",
"role": "admin",
"userScoreFantasy": {
"tournaments": [
{
"tournament_id": {
"$oid": "5e1892fb480f344830a3f160"
},
"predictions": [],
"score": null
},
{
"tournament_id": {
"$oid": "5e189f5f8d88292754e10b37"
},
"predictions": [],
"score": null
}
],
"totalScore": null
},
}

我想这样做:

  1. 查找具有预定义用户 ID 的用户
  2. 传递所有 userScoreFantasy.tournaments 数组以查找特定的锦标赛 ID
  3. 将一个像这样的对象插入找到的锦标赛预测数组中:
{
score,
"match_id": foundMatch._id
}

因此锦标赛数组将变为:

[
{
"tournament_id": {
"$oid": "5e1892fb480f344830a3f160"
},
"predictions": [
"score" : 200,
"match_id": "5e1892fb480f34faw21410"
],
"score": null
},
]

我尝试这样做:

 Users.update({
"_id": prediction.user_id,
"userScoreFantasy.tournaments": {
"$elemMatch": {
"tournament_id": foundMatch.tournament_id
}
}
}, {
"$push": {
"userScoreFantasy.tournaments.$.predictions": {
score,
"match_id": foundMatch._id
}
}
})

但是数组没有更新。

编辑:工作电话:

Users.updateOne({
"_id": ObjectID(prediction.user_id),
}, {
$addToSet: {
"userScoreFantasy.tournaments.$[element].predictions": {
score,
"match_id": foundMatch._id
}
}
}, {
arrayFilters: [{
"element.tournament_id": ObjectID(foundMatch.tournament_id)
}]
}

)

最佳答案

您应该使用position indentifier更新你的数组,如下所示:

Users.updateOne(
{
"_id": prediction.user_id,
},
{
$addToSet: {
"userScoreFantasy.tournaments.$[element].predictions": {
score,
"match_id": foundMatch._id
}
}
},
{arrayFilters: [{"element.tournament_id": foundMatch.tournament_id}]}
);

关于node.js - MongoDB 插入嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59731224/

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