I'm losing my mind a bit here. I'm completing an old project of mine with Express and Mongoose with Google firebase login. Everything was working fine with my first test user, but as soon as I tried to log in with a second new account, I got this error:
E11000 duplicate key error collection: test.users index: username_1 dup key: { username: null }
The weird thing is i dont even have the username in my schema.
I checked my models/User.js file ten times. I’m only using name, email, role, and googleId. I’m not even sending a username from my frontend.
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
role: { type: String, enum: ["founder", "mentor"], required: true },
googleId: { type: String, required: true },
//other imp fields
}, { timestamps: true });
module.exports = mongoose.model("User", userSchema);
And my route:
// This fails on user.save() for the second person who tries to sign up
const user = new User({
name: req.body.name,
email: req.body.email,
role: req.body.role,
googleId: req.body.uid
profilePicture: req.body.picture,
bio:"",
});
await user.save();
Error from logs:
MongoServerError: E11000 duplicate key error collection: test.users index: username_1 dup key: { username: null }
at InsertOneOperation.execute (/home/samiii/Documents/prabal_project/backend/node_modules/mongodb/lib/operations/insert.js:51:19)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async tryOperation (/home/samiii/Documents/prabal_project/backend/node_modules/mongodb/lib/operations/execute_operation.js:207:20)
at async executeOperation (/home/samiii/Documents/prabal_project/backend/node_modules/mongodb/lib/operations/execute_operation.js:75:16)
at async Collection.insertOne (/home/samiii/Documents/prabal_project/backend/node_modules/mongodb/lib/collection.js:157:16) {
errorLabelSet: Set(0) {},
errorResponse: {
index: 0,
code: 11000,
errmsg: 'E11000 duplicate key error collection: test.users index: username_1 dup key: { username: null }',
keyPattern: { username: 1 },
keyValue: { username: null }
},
index: 0,
code: 11000,
keyPattern: { username: 1 },
keyValue: { username: null }
}
Any help would be huge. Thanks!!
This is a classic Mongoose "ghost" index issue. Even though you don't see username in your current code or schema, MongoDB still has an old unique index stored in the database from a previous version of your schema.
When you delete a field from your Mongoose code, Mongoose does not delete the index from the actual MongoDB database.
How to Fix it.
Open MongoDB Compass and connect to your database.
Navigate to the your database and click on the users collection.
Look at the tabs at the top (Documents, Schema, Explain, etc.) and click on Indexes.
Find the index named username_1.
Click the Trash/Delete icon next to it.
Confirm the deletion by typing the name of the index.
Hope this will help..!