1

I am trying to insert an array of documents into a MongoDB collection. The collection has a unique index on one of the fields. I am inserting all the documents at once as such:

const mongojs = require('mongojs');
const db = mongojs('mongodb://username:password@address.mlab.com:37230/database');

             // documents is an array of documents
db.items.insert(documents, (err, task) => {
    if (err) {
      console.log(err);
    }
  })

Now there is one document that violates the unique index and I receive this error:

E11000 duplicate key error index: database.items.$upc_1 dup key:

Consequently, NONE of the documents get saved even though there was only one document that violated the unique index.

How do I tell Mongo to just ignore that one document and save all the others? Thanks!

Community
  • 1
  • 1
etayluz
  • 15,920
  • 23
  • 106
  • 151

1 Answers1

3

You can use the db.collection.insertMany() function with the parameter {ordered: false}. See the docs (near the bottom where they describe unordered inserts): https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/

Tyler Kirby
  • 253
  • 1
  • 10