Reputation: 2402
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!
Upvotes: 17
Views: 12393
Reputation:
Just use addToSet
method:
team.players.addToSet(player)
team.save()
Upvotes: 12