title: MongoError: E11000 duplicate key error collection for unique compound index including an ObjectId
body: <p>collection index schema and index:</p>
  
  <pre><code>const schema: Mongoose.SchemaDefinition = {
    field_name: { type: String, required: true },
    mask: { type: String, required: true },
    value: { type: String, required: true },
    register: { type: Mongoose.Schema.Types.ObjectId, ref: 'register' }
  };
  
  const indexFields = {
    field_name: 1,
    mask: 1,
    regsiter: 1,
    value: 1
  };
  
  export const RegisterFieldsSchema = new Mongoose
    .Schema(schema, { timestamps: true })
    .index(indexFields, {unique: true});
  </code></pre>
  
  <p>And the collection already has records with same <code>field</code>, <code>mask</code> and <code>value</code> as following record, but no record contains the same <code>register</code>. </p>
  
  <p>When I try to insert a document:</p>
  
  <pre><code>db.getCollection('registerfields')
  .insert({
      "field_name":"ARM_SMMU_CBn_PMEVTYPER2_0_NSU",
      "mask":"0x10000000",
      "register":ObjectId("5ae2639ffc61a6c8dbb332a5"),
      "value":"0x00000000",
  });
  </code></pre>
  
  <p>database returns:</p>
  
  <pre><code>grdb-dev.registerfields index: 
  field_name_1_mask_1_regsiter_1_value_1 dup key: 
  {
      : "ARM_SMMU_CBn_PMEVTYPER2_0_NSU", 
      : "0x10000000", 
      : null, 
      : "0x00000000"
  }
  </code></pre>
  
  <p>According to several other answers, this might caused by a document without <code>register</code> property already existed in the collection. So I checked if this is the case:</p>
  
  <pre><code>db.getCollection('registerfields')
      .find({"register":  {$exists: false}})
  </code></pre>
  
  <p>result: <code>Fetched 0 record(s) in 6ms</code></p>
  
  <p>I also run the above query to check if all documents contains <code>field_name</code>, <code>mask</code> and <code>value</code>. Got 0 record for all of </p>
  
  <p>Anyone know why the duplicate key has null for register?</p>