Duplicate data getting added into collection

Hi, I have created a mongoose model as below, and set recordId field to “unique: true” to handle duplicate entry. But when through API multiple calls are happening within milliseconds the collection is allowing duplicate entries. Can anyone please tell how to handle this error.

const RecordList = mongoose.model(
‘record_list’,
mongoose.Schema({
recordId: {
type: String,
unique: true,
required: [true, ‘Please enter record id!’],
},
campaign: {
type: String,
}
})
);

Thank You.

Hello @Krushna_Chandra_Rout, Welcome to the MongoDB Community forum!

With Mongoose ODM, when you create a field in a schema with property unique:true, it means that a unique constraint be created on that field. In fact it does create such an index in the database for that collection.

For example, the following code creates such data and inserts one document. I can verify the collection, the document and the unique index from mongosh or Compass. In the shell, db.collection.getIndexes() prints the newly created index details.

When I run the same program again, or try to insert another document with the same name: 'john', there is an error: MongoError: E11000 duplicate key error collection: test.records index: name_1 dup key: { name: "john" }.

Please include the version of MongoDB and Mongoose you are working with.

Example Code:

const mongoose = require('mongoose');
const url = 'mongodb://127.0.0.1:27017/test';
mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });

const Schema = mongoose.Schema;
var RecordSchema = new Schema({
     name: { type: String, required: true, unique: true }
}, { collection: 'records' })

const Record = mongoose.model('Record', RecordSchema);

const r1 = Record({ name: 'john' });
r1.save(function(err) { 
	if (err) throw err;
	console.log('r1 record saved.');
});

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).

Hi, @Prasad_Saya Thank You for this solution.
Actually one of unique field was deleted from compass bymistakely that’s why the above error was comming.

Thank You.

That is a bad situation. Database objects like collections, databases, indexes, etc., need to be carefully and securely managed.