Im working on an API for a custom game and i need to update specific fields in an array in my Database Entry. How do i do that without adding a new thing to the array, instead just updating for example the content of entry 5 in the array
Asked
Active
Viewed 71 times
1 Answers
1
Hello I'm not sure the name of your schema so I'm assuming its called Game so here is an example for how to update an index in an array assuming its the board array field you're trying to update. Also reference here for more details on updating an array field by it's index:
var fieldPosition = "board." + req.params.field
await Game.updateOne({
_id: 1
}, [{
$set: {
tempBoard: fieldPosition
}
},
{
$set: {
"$tempBoard": session.turn
}
},
{
$unset: ["tempBoard"]
}
])

Xanik
- 365
- 3
- 9
-
Sorry, that i didnt give enough information. This basically works, but how do i say that it changes the content of board.`req.params.field` (basically with variable)? I tried this, but it doesnt start anymore (`Unexpected token '+'`) ```js await sessionCollection.updateOne({sessionId: session.sessionId}, {$set: {"board."+req.params.field: session.turn}}); ``` – DNAScanner May 15 '22 at 14:31
-
1while not create a variable and try it like: var board = "board" + req.params.field then you can use it as: `sessionCollection.updateOne({sessionId: session.sessionId}, {$set: {board: session.turn}});` – Xanik May 15 '22 at 15:31
-
I've tried this, but it doesnt update ```js var fieldPosition = "board." + req.params.field; var setField = await sessionCollection.updateOne({sessionId: session.sessionId}, {$set: {fieldPosition: session.turn}}); ``` – DNAScanner May 15 '22 at 16:05
-
I updated the solution, try that – Xanik May 15 '22 at 17:01
-
Gives me error: https://pastebin.com/iKLTukXm – DNAScanner May 15 '22 at 17:08