Running into E11000 duplicate key errors with insertMany() - Nodejs - something in my code perhaps?

Basically I have a recursive function that returns an array of results at the end. I’m using an event emitter to return the results .

const parseDirectory = (all, results) => {
  if (!all.length) {
    return myEmitter.emit('results', results);

My event handler seems to work as far as receiving the results -

myEmitter.on('results', async arr => {
    console.log(arr) - // can see results
    await music.insertMany(arr).then(result => console.log(result));

What’s happening is the insertions are done but for some weird reason it looks like it’s attempting to do the operation again maybe ? Is there something wrong with the code, seems pretty straight forward to me. I know emitters are generally synchronous but even with asynchronous on it is getting the array correctly.
Perhaps something I need to change in my writeconcern ? currently it’s the default write concern.

Most likely your results array is not emptied between multiple myEmitter.emit() so you keep calling insertMany() with the same documents, hence the duplicate key.

Your error is not in the code you posted but in the code where you call parseDirectory().

1 Like

Okay, thank you. I dropped the emitter and use a callback for parseDirectory()'s return , works now.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.