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

210
Visualizações
Mongodb ordered option doesn't work when using insertMany method in Nodejs

I am using Mongodb in my app. It is version 4.4.1. I have set unique option in the word field to true.

And I use this code:

try {
    const words = [
      { word: "her" },
      { word: "her" },
      { word: "gathered" },
      { word: "together" },
      { word: "and" },
      { word: "rather" },
    ];

    const result = await wordsDb
      .collection
      .insertMany(words, { ordered: false });

    console.log(result.insertedCount); // nothing to console
  } catch (error) {
    console.log(error.message); // E11000 duplicate key error index: word_1 dup key: { word: "her" }
  }

It still gives the "duplicate key error". Why is it happening? Thanks.

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

If you set a unique constraint in the word field, you cannot insert in the collection 2 documents with the same value ('her') for the word field.

And you cannot bypass the constraint with the {ordered: true} option.

Indeed, throwing the error doesn't mean that other documents are not inserted. Did u check if they were inserted? If I try with an example similar to yours (not in Node but in MongoDb Compass), I get the error too, but the documents are all inserted in the collection (except for the one with the duplicate key, obviously, that is inserted only once).

Also, consider that the insert error thrown causes the code to jump immediately to the catch(error) block, so your console.log(result.insertedCount) can not be showed.

about 4 years ago · Santiago Trujillo 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