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!
To insert records in MongoDB and avoid duplicates, use “unique:true”.
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.
$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.
findById returns the document where the _id field matches the specified id . If the document is not found, the function returns null .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With