Avoid duplicate entries in a Mongoose array

I have many, many relationships using mongoose, which is as follows.

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

What I want to do is make sure that one player does not appear twice in the team.

When I do this:

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

If I have already added a player before, I see player identifiers twice in the doc team. Is there any mongo / mongoose flag that I can set so that the save method throws an exception or doesn't add a player. I know I can do a manual check, but I would prefer a simpler solution.

Thanks!

+8
mongodb mongoose
source share
2 answers

Use the update statement $addToSet , for example:

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

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

+20
source share

Just use the addToSet method:

 team.players.addToSet(player) team.save() 
+5
source share

All Articles