Error E11000 duplicate key error when i try to update

export const updateContact = async (req, res) => {
  const { body } = req;
  const { id } = req.params;
 

  try {
    const updatedContact = Contact.findByIdAndUpdate(id, body, { new: true });
   
    return res.status(200).json({ message: completed update, status: true, updatedContact });
  } catch (error) {
    return res.status(500).json({ error: error.message, status: false });
  }
}

when executing the function, it searches and updates but then throws the following error:

/home/carlos/Desktop/react-jorge/node_modules/mongoose/node_modules/mongodb/lib/operations/insert.js:50
                return callback(new error_1.MongoServerError(res.writeErrors[0]));
                                ^

MongoServerError: E11000 duplicate key error collection: J&N_DB.contacts index: _id_ dup key: { _id: ObjectId('6487c4ea43cb7181f66ca9c5') }
    at /home/carlos/Desktop/react-jorge/node_modules/mongoose/node_modules/mongodb/lib/operations/insert.js:50:33
    at /home/carlos/Desktop/react-jorge/node_modules/mongoose/node_modules/mongodb/lib/cmap/connection_pool.js:327:25
    at /home/carlos/Desktop/react-jorge/node_modules/mongoose/node_modules/mongodb/lib/sdam/server.js:207:17
    at handleOperationResult (/home/carlos/Desktop/react-jorge/node_modules/mongoose/node_modules/mongodb/lib/sdam/server.js:323:20)
    at Connection.onMessage (/home/carlos/Desktop/react-jorge/node_modules/mongoose/node_modules/mongodb/lib/cmap/connection.js:213:9)
    at MessageStream.<anonymous> (/home/carlos/Desktop/react-jorge/node_modules/mongoose/node_modules/mongodb/lib/cmap/connection.js:59:60)
    at MessageStream.emit (node:events:513:28)
    at processIncomingData (/home/carlos/Desktop/react-jorge/node_modules/mongoose/node_modules/mongodb/lib/cmap/message_stream.js:124:16)
    at MessageStream._write (/home/carlos/Desktop/react-jorge/node_modules/mongoose/node_modules/mongodb/lib/cmap/message_stream.js:33:9)
    at writeOrBuffer (node:internal/streams/writable:392:12) {
  index: 0,
  code: 11000,
  keyPattern: { _id: 1 },
  keyValue: {
    _id: ObjectId {
      [Symbol(id)]: Buffer(12) [Uint8Array] [
        100, 135, 196, 234,
         67, 203, 113, 129,
        246, 108, 169, 197
      ]
    }
  },
  [Symbol(errorLabels)]: Set(0) {}
},

every attempt to update gives me the same error even though I have only one object in my collection

Hi @carlos_barreto and welcome to MongoDB community forums!!

From the error message, it seems you are trying to update the _id to a value that already exists in the collection. To understand further. can you help me with a sample code?

I tried to create a sample data as:

test> db.sampletest.find()
[
  { _id: ObjectId("648aec7ada6163c9fbd6fdee"), name: 'wbc', age: 6 },
  { _id: '123', age: 8, name: 'abc' }
]
test>

and tried the following mongoose code for the following:

const mongoose = require('mongoose');

// Connect to the MongoDB database
mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => {
    console.log('Connected to the database');
  })
  .catch((error) => {
    console.error('Error connecting to the database:', error);
  });

// Define the schema for the collection
const sampleTestSchema = new mongoose.Schema({
  name: String,
  age: Number
});
console.log(sampleTestSchema);

// Create a model for the collection
const SampleTest = mongoose.model('sampletest', sampleTestSchema);

// Update a document by its ID using findByIdAndUpdate
const updateDocumentById = async (id, newData) => {
    console.log(id,newData);
  try {
    const updatedDocument = await SampleTest.findByIdAndUpdate(id, newData);
    console.log('Updated document:', updatedDocument);
  } catch (error) {
    console.error('Error updating document:', error);
  }
};

const idToUpdate = new mongoose.Types.ObjectId('648aec7ada6163c9fbd6fdee');
const newData = { name: 'ABC', age: 30 };
updateDocumentById(idToUpdate, newData);

and it has worked for me.

Let me know if this helps.

Regards
Aasawari