Duplicate data getting added into collection

This may be that the index is created through Mongoose with background: true option. This option may not create the index immediately, and this allows duplicate entries on the indexed field.

An option for you is to create the index from mongosh or Compass initially. You can still keep the Mongoose definition as it is. This will definitely trigger duplicate data error immediately.


A quick query on my index data showed that the index is created with background:true option [*]:

       {
               "v" : 2,
               "unique" : true,
               "key" : {
                       "name" : 1
               },
               "name" : "name_1",
               "ns" : "test.records",
               "background" : true       // <---- [*]
       }

NOTE: This was with using Mongoose 6.2.4 and MongoDB v.5.0.6 (Atlas Cluster).