Jessie Emerson
Jessie Emerson

Reputation: 743

duplicated key of id in mongodb

This code won't work, I got error of E11000 duplicate key error index error.

Student.update({_id: id, 'data.date':date}, {'$set': {'data.score': 50}}, {upsert: true}, 
    function(err,result) {
        res.json(1);
  });

I have no clue how to solve it when I can do

  Student.findOne({_id: id}, function(err,result){
          res.json(result)
        })

Any clue what's going on?

Upvotes: 0

Views: 107

Answers (1)

rsp
rsp

Reputation: 111506

I see two possible problems:

  1. You may have set some of the fields as unique and Mongo created an index for that field. For example if data.score would be unique then you couldn't have two documents with the same value and maybe other document already has a value of 50.

The solution would be to search for indexes and remove the ones that you don't want.

  1. Maybe your search for {_id: id, 'data.date': date} doesn't return a result but not because you don't have a document with that id, but because it doesn't have that 'data.date' field that you search for. Then the upsert tries to insert a new document (because the search didn't find anything that has both '_id' equal to id and 'data.date' equal to date) but it fails to do so (because you already have a document with '_id' equal to id).

The solution would be to search only by _id if you're using upsert.

Upvotes: 2

Related Questions