Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

595
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda