title: MongoError: E11000 duplicate key error collection: users index: mobile_1 dup key: { mobile: null }
body: <p>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:</p>
  
  <h3>The 'mobile' key inside my user schema</h3>
  
  <pre><code>mobile: {
    type: String,
    index: {
      unique: true,
      partialFilterExpression: { mobile: { $type: 'string' } }
    },
  }
  </code></pre>
  
  <h3>mongoose debug log</h3>
  
  <pre><code>Mongoose: users.createIndex({ mobile: 1 }, { unique: true, partialFilterExpression: { mobile: { '$type': 'string' } }, background: true})
  </code></pre>
  
  <h3>Error</h3>
  
  <pre><code>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)]: {}
  }
  </code></pre>
  
  <p>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.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>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.</p>