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
1 Answer
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"]
}
])
5 Comments
DNAScanner
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}}); Xanik
while 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}});DNAScanner
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}}); Xanik
I updated the solution, try that
DNAScanner
Gives me error: pastebin.com/iKLTukXm