MongoDB Error Code 11000, how to prevent shutdown

Hello! I currently have an application running using Node.js and Express that takes data from ParseHub and feeds it into a MongoDB database at certain intervals. I also have a unique index set up with ordered: false so that no duplicate data from different runs will feed into the database. When the application runs I get error code 11000, which is what I want it to do as I want it to catch and not add duplicate entries. However, the server shuts down because of the errors. How can I either keep the server running or restart it after encountering errors? My code is below. I have tried forever and pm2 and didn’t have any luck, the server didn’t restart.

const options = {ordered: false}

.then(csvData => {
    { useNewUrlParser: true, useUnifiedTopology: true },
    (err, client) => {
      if (err) throw err;
        .insertMany(csvData, options);

Hi @HD_Roofers

What you need is a try catch statement to catch the error that insertMany() throw, and handle that error accordingly. Please see the insertMany() example, where it shows the use of try catch in the Javascript example.

In addition, you might find the page Error handling in Node.js useful.

Best regards