1

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 1

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"]
  }
])

Sign up to request clarification or add additional context in comments.

5 Comments

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}});
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}});
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}});
I updated the solution, try that
Gives me error: pastebin.com/iKLTukXm

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.