17

I have a many to many relation using mongoose, that looks like this.

TeamSchema = new Schema 
    name : String
    players: [{ type: ObjectId, ref: 'Player' }]

What I want to do is ensure that one Player doesnt appear two times in a Team.

When I do:

team.players.push(player)
team.save()

If I already added the player before, I see the players id two times on the team doc. Is there some kind of mongo/mongoose flag I can set so that the save method throws an exception, or doesn't add the player. I know I could do the check by hand, but I would prefer a simpler solution.

Thanks!

2 Answers 2

37

Use the $addToSet update operator like so:

Team.update({_id: team._id}, {$addToSet: {players: player}})

Assuming player is the ObjectId of a player, it will only be added to the team's players array if it's not already present.

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

Comments

12

Just use addToSet method:

team.players.addToSet(player)
team.save()

Comments

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.