1

I've created a model with a set matches in it. However every time I update a document, it just adds the match to matches, which results in duplicates. I'm wondering whether there is a method that lets me specify a key, in my case the matchId, and if it already exists in the matches set it should update that particular object in the set?

Model

var leagueSchema = new Schema({
    _id: Number,
    name: String,
    league: Number,
    matches: [{
        matchId: Number,
        date: Date,
        tournament: String,
        homeName: String,
        awayName: String,
        awayScore: Number,
        homeScore: Number,
        homeLogo: String,
        awayLogo: String
    }]
});

Update Query

var queryData = {'matchId': matchId, 'date': date, 'tournament': tournament, 'homeName': homeTeam, 'awayName': awayTeam, 'awayScore': awayScore, 'homeScore': homeScore, 'homeLogo': homeLogo, 'awayLogo': awayLogo};

League.update({league: leagueId}, {$addToSet: {matches: queryData}})
    .exec(function(err, update) {
});
sheilak
  • 5,833
  • 7
  • 34
  • 43
Peter Pik
  • 11,023
  • 19
  • 84
  • 142
  • @JohnnyHK I think this question is a little bit different. In this case we need to update match record if one exists with the same matchId key. Thus it's not duplicate, and your answer isn't a full solution for this question. – Rashad Ibrahimov Nov 15 '15 at 15:28
  • @RashadIbrahimov Got ya, I didn't catch that the first time, thanks. – JohnnyHK Nov 15 '15 at 15:33

1 Answers1

0

You can make your filter more precise. You can exclude (with $ne) items in your matches array when the matchId was found. When your matchId in your matches was found, it will not "find" the document and therefore not update the document. (I know it is confusing!) Your query will look like this:

League.update({league: leagueId, 'matches.matchId': {$ne: matchId}}, {$addToSet: {matches: queryData}})
    .exec(function(err, update) {
        // Do something
    });
Thomas Bormans
  • 5,156
  • 6
  • 34
  • 51