thomas g
thomas g

Reputation: 35

Mongodb $addToSet duplicates

I'm building an app with mongodb and node js. It is about creating polls, and I want to add new options on database and increase the number of votes for each submit. All works fine but on the first search it duplicates the option rather than just update the vote here is the code:

let newChoice = function(option) { this.option = choice; this.votes = 0; };        let New = new newChoice(choice);
poll.update({_id: id}, {$addToSet: {"options": New, $exists: false}}, function(err, doc){
  if (err) {
    console.log(err);
  } 
  else {
      console.log(doc)
  }
}); 
poll.update({_id: id, "options.option": choice}, {$inc: {"options.$.votes": 1}}, function(err, vote) { if (err) { console.log( err); } });
    res.redirect("/show/"+id);
});

and here is the way that I store on db "options":

[ { "option": " pizza", "votes": 0 }, { "option": "burger ", "votes": 0 } 

Any idea how to prevent duplicates?

Upvotes: 0

Views: 594

Answers (1)

Rahul
Rahul

Reputation: 16355

You may conditionally insert if the option with your choice and votes=0 doesn't exist already

db.coll.update(
    {_id: id, 'options.option': {$ne: my_choice}}, 
    {$push: {options: {'option': my_choice, 'votes': 0}}});

After this operation, your update command for incrementing the count will work as expected.

Upvotes: 1

Related Questions