Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 599
martinpaulucci Avatar asked Nov 15 '12 19:11

martinpaulucci


People also ask

How do I stop MongoDB from inserting duplicate records?

To insert records in MongoDB and avoid duplicates, use “unique:true”.

What does unique do in mongoose?

The unique option tells Mongoose that each document must have a unique value for a given path. For example, below is how you can tell Mongoose that a user's email must be unique. const mongoose = require('mongoose'); const userSchema = new mongoose.

What is $Push in mongoose?

$push. The $push operator appends a specified value to an array. The $push operator has the form: { $push: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.

What does Mongoose findById return?

findById returns the document where the _id field matches the specified id . If the document is not found, the function returns null .


1 Answers

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.

like image 139
JohnnyHK Avatar answered Oct 11 '22 22:10

JohnnyHK