Muirik
Muirik

Reputation: 6289

Duplicate Key Error on MongoDB Model, Even When Model is Not Enforcing Uniqueness for that Value

In my app I have an endpoint that allows a user to create a new document by simply passing something like this:

{ name: { long: "some name" } }

Now, the relevant portion of the model for this document looks like this:

name: {
  long: {
    type: String,
    trim: true
  },
  short: {
    type: String,
    trim: true
  }
}

As you can see, I don't have "short" set to "unique: true". However, the user is getting this error:

 "errmsg": "E11000 duplicate key error collection: hr.agencies index: name.short_1 dup key: { : null }"

So, clearly the problem here is that once you have more than one "name.short" with a value of null, its producing a dupe error. However, since I don't have unique set to true in the model, I'm not sure why it's enforcing this as a rule.

What could the issue be here, and how can I resolve it? Is there a way I can explicitly say, don't enforce uniqueness on this field?

Upvotes: 2

Views: 43

Answers (1)

Ashh
Ashh

Reputation: 46461

Try to remove the index from the short key using

db.collection.dropIndex({ "name.short": 1 })

Upvotes: 1

Related Questions