简体   繁体   English

Mongo DB 推送到对象数组?

[英]Mongo DB Push to Array of Objects?

Working on a project that uses MongoDB as a database.从事使用 MongoDB 作为数据库的项目。 I'm stuck on trying to get an array of objects I have to update.我一直在尝试获取必须更新的对象数组。 Here is the schema:这是架构:

roundData : {
                playsArray : [ 
                    {
                        player1 : {
                            card1 : 1,
                            card2 : 2
                        },
                        player2 : {
                            card1 : 0,
                            card2 : 0
                        }
                    },
                ],

So basically I want a single array that holds an object within that object are two objects.所以基本上我想要一个包含 object 的单个数组,其中 object 是两个对象。

Plays Array [ object1, object2] where object 1 would be {player 1: {card1: 0, card2: 0}}, {player 2: {card1: 0, card2: 0}}.播放数组 [object1, object2],其中 object 1 将是 {player 1: {card1: 0, card2: 0}},{player 2: {card1: 0, card2: 0}}。

Every time I try to write an updateOne function, it at best only updates player 1 or it seperates player 1 and player 2 as two items in the array.每次我尝试编写 updateOne function 时,它最多只更新玩家 1,或者将玩家 1 和玩家 2 作为数组中的两个项目分开。 Any suggestions what I'm doing wrong on the formating?有什么建议我在格式上做错了吗?

Here's my current code:这是我当前的代码:

const gameData = await GameData.updateOne({ gameId: gameIdInput }, { $push: { "matchData.roundData.playsArray": { $each : [ {"player1" : {"card1" : 0, "card2" :0} }, {"player2" : {"card1" : 0, "card2" :0} } ] } } } );

This works, but it pushes player 1 and player 2 into the array separately so that the array becomes [ player 1/2 objects, player 1 objects, player 2 objects ].这行得通,但它会将玩家 1 和玩家 2 分别推入数组,以便数组变为 [玩家 1/2 对象、玩家 1 对象、玩家 2 对象]。

Nevermind.没关系。 I was missing [ ] around the object in a previous version without $each.在没有 $each 的先前版本中,我在 object 周围缺少 [ ]。 Leaving here for solution if anyone finds it helpful.如果有人觉得有帮助,请离开这里寻求解决方案。

const gameData = await GameData.updateOne({ gameId: gameIdInput }, { $push: { "matchData.roundData.playsArray": [ {"player1" : {"card1" : 0, "card2" :0} }, {"player2" : {"card1" : 0, "card2" :0} } ]  } } );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM