martinpaulucci
martinpaulucci

Reputation: 2402

Avoid duplicate entries on Mongoose array

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

Answers (2)

user1882644
user1882644

Reputation:

Just use addToSet method:

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

Upvotes: 12

JohnnyHK
JohnnyHK

Reputation: 311835

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.

Upvotes: 37

Related Questions