Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

212
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda