Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

598
Views
MongoServerError: E11000 duplicate key error collection: with mongoose save()

i have this model with username and email set uniqe to false

const UserSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
    minlength: 3,
    maxlength: 20,
    unique: false,
  },
  email: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 64,
    lowercase: true,
    unique: false,
  },
  mailboxLink: {
    type: String,
    required: true,
    unique: true,
    default: nanoid(),
  },
  createdat: { type: String, default: dateJakarta },
});

and 1 user in my mongodb database

{"_id":{"$oid":"622eec9de7f66d1d633061e7"},"username":"jhon","email":"email@gmail.com","mailboxLink":"mfdYTDK","createdat":"2022-03-14 14:19:01","__v":0}

but when i'm trying to register the same username and email

userRouter.post("/register", async (request, response) => {
  const newUser = new userSchema(request.body); // body: {username, email}
  await newUser.save((err, user) => {
    if (err) {
      console.log(err);
    } else {
      const token = newUser.generateAuthToken();
      response.status(201).json({
        token,
        user,
        message: "Register successfully",
      });
    }
  });
});

i got this error from console.log(err);

MongoServerError: E11000 duplicate key error collection: PigeonProjekt.users index: email_1 dup key: { email: "email@gmail.com" }


  index: 0,
  code: 11000,
  keyPattern: { email: 1 },
  keyValue: { email: 'email@gmail.com' }

could someone help me solve this problem.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If you can, try dropping the database or the collection itself then test again. If you first set the email field to unique: true and then inserted the user that you have in the database, but later changed the unique value of email to false in your schema, this will not update the collection itself. In short, rules in the database for email unique: true still apply and you need to remove them.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!