Avoid duplicate entries on Mongoose array

后端 未结 2 1376
深忆病人
深忆病人 2020-12-31 09:59

I have a many to many relation using mongoose, that looks like this.

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


        
相关标签:
2条回答
  • 2020-12-31 10:16

    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.

    0 讨论(0)
  • 2020-12-31 10:31

    Just use addToSet method:

    team.players.addToSet(player)
    team.save()
    
    0 讨论(0)
提交回复
热议问题