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

export const registerUser = asyncHandler(async (req, res) => {
const { fullName, email, password, phone, address, role} = req.body;

console.log(‘Incoming registration request:’, req.body); // Debugging log

const missingFields = ;
if (!fullName?.trim()) missingFields.push(‘fullName’);
if (!email?.trim()) missingFields.push(‘email’);
if (!password?.trim()) missingFields.push(‘password’);
if (!phone?.trim()) missingFields.push(‘phone’);
if (!address?.trim()) missingFields.push(‘address’);

if (missingFields.length > 0) {
throw new ApiError(400, The following fields are required: ${missingFields.join(', ')});
}

// Normalize email and fullName to lowercase
const normalizedEmail = email.trim().toLowerCase();
const normalizedFullName = fullName.trim().toLowerCase();

const existingUser = await User.findOne({
$or: [{ email: normalizedEmail }, { fullName: normalizedFullName }]
});
if (existingUser) {
throw new ApiError(409, ‘User with this email or username already exists’);
}

// create user obj by coping data from req.body
// check only if the email exists in the database
// if it does, throw an error
// if it doesn’t, create a new user
// check whether it was inserted
// remove password and refreshToken from the response

try {
const user = await User.create({
fullName: normalizedFullName,
email: normalizedEmail,
password,
phone,
address,
role
});
const createdUser = await User.findOne({email:normalizedEmail}).select(“-password -refreshToken”);
const options = {
httpOnly: true,
secure: true
}

res.status(201)
.cookie("accessToken", user.generateAccessToken(), options).cookie("refreshToken", user.generateRefreshToken(), options)
.json(new ApiResponse(201, createdUser, 'User registered successfully'));

} catch (error) {
if (error.code === 11000) {
console.error(‘Duplicate key error:’);
throw new ApiError(409, Duplicate key error:);
}
throw new ApiError(500, ‘Internal Server Error’);
}
}); this is my controller while i am signuping this error is coming can you help me out of this: Duplicate key error:
Error: Duplicate key error:
at file:///C:/Users/2388128/OneDrive%20-%20Cognizant/Desktop/New%20folder/interiumproject/backendmodels/src/controllers/user.controller.js:82:13
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)