Home > Software design >  Getting a e11000 duplicate key error when trying to create new user with mongodb
Getting a e11000 duplicate key error when trying to create new user with mongodb

Time:04-15

I am getting this error when i try to create a user E11000 duplicate key error collection: rajTech.users index: isAdmin_1 dup key: { isAdmin: false }

My user Schema is

import mongoose from 'mongoose'

const userSchema = new mongoose.Schema(
    {
        name: {type: String, required: true},
        email: {type: String, required: true, unique: true},
        password: {type: String, required: true},
        isAdmin: {type: Boolean, default: false, required: true, unique: true},
        
    },
    {
        timestamps:true
    }
)
const User = mongoose.model('User', userSchema)
export default User

This is my function

userRouter.post(
    '/signup',
    expressAsyncHandler(async (req, res) => {
        const newUser = new User({
            name: req.body.name,
            email: req.body.email,
            password: bcrypt.hashSync(req.body.password)
        })
        const user = await newUser.save()
        res.send({
            _id: user._id,
            name: user.name,
            email: user.email,
            isAdmin: false,
            token: generateToken(user)
    })
    }))

CodePudding user response:

Remove unique: true from isAdmin field. Then you need to drop the index from the database db.user.dropIndexes()

  • Related