title: Duplicate null key value error MongoDB with Mongoose
body: <p>I'm trying to add a user to my users collection and keep getting a duplicate null key value error.</p>
  
  <p>My Users model used to look like this like this:</p>
  
  <pre><code>const mongoose = require("mongoose");
  
  const UserSchema = new mongoose.Schema({
    name: {
      type: String,
      required: true
    },
    email: {
      type: String,
      required: true,
      unique: true
    },
    profilePictures: [{
      link: {
         type: String
      }
      rank: {
         type: Number,
         unique: true
      }
    }],
  });
  
  module.exports = User = mongoose.model("users", UserSchema);
  
  </code></pre>
  
  <p>Before I changed the pictures field to </p>
  
  <pre><code>...
  pictures = []
  ...
  </code></pre>
  
  <p>I believe because I saved users under the former schema, it has saved somewhere the model of the object in the pictures array (they would be given an ObjectId when I saved something to that array).
  Even though I have changed the field to </p>
  
  <pre><code>pictures = []
  </code></pre>
  
  <p>I still get this error</p>
  
  <pre><code>E11000 duplicate key error collection: testDB.users index: profilePictures.rank_1 dup key: { profilePictures.rank: null }
  </code></pre>
  
  <p>When neither profilePictures nor rank fields even exist anymore.
  I imagine I can probably just delete the users collection and start again but I want to know if there is a better way to handle this error? Suppose I had 100 users in the users collection – I wouldn't be able to just delete them all.
  Thanks!</p>