I have this mongoDB document structure:
Game = {
_id: 'randomObjectId',
players: [Array of players ObjectIds],
maxPlayers: 2,
status: 'created' (or 'fully-booked')
}
When a new player joins the game I want to add him to the players array and change the status of the game to fully-booked only if this condition is met: players.length < maxPlayers.
To recap:
- Check inside the DB(using the query) if
players.length < maxPlayers; - If yes update the document
- If no send back an error response (optional)
Without this check it's easy to make the query using:
Game.findByIdAndUpdate('randomObjectId', {
$addToSet: {
players: 'playerObjId'
},
gameStatus: 'fully-booked'
}, {
new: true
})
What I don't know is how to add this condition to this (or other type of) query. Any help is appreciated. Thanks
findAndModifyhere.$setis irrelevant here, though? Or am I missing something?