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

206
Views
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 answers
Answer question

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 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!