mongoosemobilecollectionsduplicateskey

MongoError: E11000 duplicate key error collection: users index: mobile_1 dup key: { mobile: null }


I created a user schema where I have a mobile field. The mobile field should be unique but still allow null values and should only compare uniqueness with strings. Here's my debug info:

The 'mobile' key inside my user schema

mobile: {
  type: String,
  index: {
    unique: true,
    partialFilterExpression: { mobile: { $type: 'string' } }
  },
}

mongoose debug log

Mongoose: users.createIndex({ mobile: 1 }, { unique: true, partialFilterExpression: { mobile: { '$type': 'string' } }, background: true})

Error

MongoError: E11000 duplicate key error collection: users index: mobile_1 dup key: { mobile: null }
    at Function.create (~/project/node_modules/mongodb/lib/core/error.js:44:12)
    at toError (~/project/node_modules/mongodb/lib/utils.js:150:22)
    at ~/project/node_modules/mongodb/lib/operations/common_functions.js:265:39
    at handler (~/project/node_modules/mongodb/lib/core/sdam/topology.js:971:24)
    at ~/project/node_modules/mongodb/lib/core/sdam/server.js:496:5
    at ~/project/node_modules/mongodb/lib/core/connection/pool.js:420:18
    at processTicksAndRejections (internal/process/task_queues.js:75:11) {
  driver: true,
  name: 'MongoError',
  index: 0,
  code: 11000,
  keyPattern: { mobile: 1 },
  keyValue: { mobile: null },
  errmsg: 'E11000 duplicate key error collection: users index: mobile_1 dup key: { mobile: null }',
  [Symbol(mongoErrorContextSymbol)]: {}
}

I tried a lot of options and different answers from stackoverflow but nothing seems to work so I'd like ask the proper way of doing this.

EDIT

The issue was that the code I had was correct, but I had to delete and re-create the table for it to work. Another solution would be to just remove the indexes.


Solution

  • The issue was that the code I had was correct, but I had to delete and re-create the table for it to work. Another solution would be to just remove the indexes.