Home > Software engineering >  Mongodb ordered option doesn't work when using insertMany method in Nodejs
Mongodb ordered option doesn't work when using insertMany method in Nodejs

Time:04-25

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.

CodePudding user response:

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.

  • Related