Error E11000 when trying to register a new user

Hi everyone,
I have a beginners’ problem that I would appreciate your help with, I have this code for registration in my app.js code:


///Register new user
app.post('/register', async (req, res) => {
    try {
        console.log('Received registration request:', req.body);

        const { username, email, password } = req.body;

        const existingUser = await User.findOne({ email });

        if (existingUser) {
            console.log('Email already registered:', email);
            return res.status(400).send('Email already registered');
        }

        const newUser = new User({
            username, 
            email,
            password,
        });

        await newUser.save();

        console.log('User registered successfully:', newUser);
        
        res.cookie('userId', newUser._id.toString(), { httpOnly: true });

        res.redirect('/'); 
    } catch (error) {
        console.error('Error processing user registration:', error);

        res.status(500).json({ error: error.message, stack: error.stack });
    }
});
////////////////////

This is the user.js file:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt');

const UserSchema = new Schema({
    username: {
        type: String,
        required: true,
    },
    password: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    }
});

UserSchema.methods.comparePassword = async function(candidatePassword) {
    try {
        return await bcrypt.compare(candidatePassword, this.password);
    } catch (error) {
        throw new Error(error);
    }
};

UserSchema.pre('save', function(next){
    const user = this;
    

    if (!user.isModified('password')) return next();

    bcrypt.hash(user.password, 10, (error, hash) => {
        if (error) return next(error);
        user.password = hash;
        next();
    });
});

const User = mongoose.model('User', UserSchema);
module.exports = User;
////////////

It lets me register one user then when I try to register a new one it give me this error in the VSCode terminal:

Received registration request: { username: 'test', email: 'test@test.com', password: '555' }
Error processing user registration: MongoServerError: E11000 duplicate key error collection: IndexPulse.users index: name_1 dup key: { name: null }
    at InsertOneOperation.execute (C:\Work\code\test9\node_modules\mongodb\lib\operations\insert.js:48:19)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async executeOperationAsync (C:\Work\code\test9\node_modules\mongodb\lib\operations\execute_operation.js:106:16) {
  index: 0,
  code: 11000,
  keyPattern: { name: 1 },
  keyValue: { name: null },
  [Symbol(errorLabels)]: Set(0) {}
}

What do you think I should do in that case?

Thanks.

Hey @Tal_Ya,

Welcome to the MongoDB Community forums :sparkles:

Looking at the error message it seems you have created a unique index on the name field, because of this you are getting the E11000: Duplicate key error.

May I ask if there is any specific reason for creating a unique index on the name?

It’s worth noting that you can’t insert the name as null twice, as null is considered to be a particular value. If you have the requirement to create a unique index while ignoring null values, please consider creating a sparse index.

I hope this helps!

Regards,
Kushagra

Hi, thanks for the reply.

There is no ‘unique: true’ line in the user.js model, although I think it makes sense that the user name would be unique to the user, I might be wrong here, still I’m a newbie, anyways this is the user.js model:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt');

const UserSchema = new Schema({
    username: {
        type: String,
        required: true,
    },
    password: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    }
});

UserSchema.methods.comparePassword = async function(candidatePassword) {
    try {
        return await bcrypt.compare(candidatePassword, this.password);
    } catch (error) {
        throw new Error(error);
    }
};

UserSchema.pre('save', function(next){
    const user = this;
    
    if (!user.isModified('password')) return next();

    bcrypt.hash(user.password, 10, (error, hash) => {
        if (error) return next(error);
        user.password = hash;
        next();
    });
});

const User = mongoose.model('User', UserSchema);
module.exports = User;

You can also see that I named the ‘name’ field: ‘username’, and not ‘name’, I don’t know if it has something to do with the error.

Do you see anything unusual about the model?

Could be due to an earlier version of the model, drop the index.

Clearly this index is the issue.
IndexPulse.users index: name_1 dup key: { name: null }

You were right, I’ve had an old version of the index in this specific collection.
I dropped the old index and now everything works.

Thanks a lot!