title: MongoDB Duplicate Key Error
body: <p>So right now, I'm working on a service to allow multiple events to store data on MongoDB. They store event data by creating new collections on MongoDB every time a new event comes on. If the same event needs to store a different set of data, a new document in MongoDB should be created.</p>
  
  <p>The code below is the service I created to handle this.    </p>
  
  <pre><code>import WhiteBoardEvent from '../model/event.model';
  import IEventStore from '../interface/eventStore.interface';
  import * as MongoClient from 'mongodb';
  
  export class EventStore implements IEventStore {
      private mongoDBEndpoint = "mongodb://192.168.10.10:27017";
  
  
      public insert(event: WhiteBoardEvent, callback: (err: any) =&gt; void): void {
          MongoClient.connect(this.mongoDBEndpoint, { connectTimeoutMS: 1000 }, (connErr, db) =&gt; {
              if (connErr) { db.close(); callback(connErr); return; }
              this.getNextSequence(db, event, (err, sequence) =&gt; {
                  if (err) { db.close(); callback(err); return; }
                  event.sequence = sequence;
                  db.collection(event.roomId).insert(event, (err) =&gt; {
                      db.close();
                      callback(err);
                  });
              });
          });
      }
  
      private createCounterCollection(db: MongoClient.Db, event: WhiteBoardEvent, callback: (err: any) =&gt; void): void {
          db.collection("counters").insert({
              roomId: event.roomId,
              sequence: 0
          }, callback);
      }
  
      private getNextSequence(db: MongoClient.Db, event: WhiteBoardEvent, callback: (err: any, sequence: number) =&gt; void): void {
          var collection = db.collection("counters");
          collection.findOneAndUpdate(
              { roomID: event.roomId },
              {
                  $inc: { sequence: 1 },
                  // new: true
              },
              {
                  upsert: true,
                  returnOriginal: false
              },
              (err, r) =&gt; {
                  if (err) {
                      this.createCounterCollection(db, event, (err) =&gt; {
                          if (err) { callback(err, -1); return; }
                          callback(null, 0);
                      });
                      return;
                  }
                  callback(null, r.value.sequence);
                  console.log("counter : " + r.value.sequence);
              }
          );
      }
  }
  </code></pre>
  
  <p>The following code is a test file I created so that I can see the changes in MongoDB.</p>
  
  <pre><code>import * as timers from 'timers';
  import WhiteBoardEvent from './data/model/event.model';
  import { EventStore } from './data/service/eventStore.service';
  
  var model = new WhiteBoardEvent();
  model.name = "t2";
  model.roomId = "testRoom";
  model.timestamp = new Date();
  model.userId = "";
  
  
  var model2 = new WhiteBoardEvent();
  model2.name = "t1";
  model2.roomId = "testRoom2";
  model2.timestamp = new Date();
  model2.userId = "";
  
  var eventStore = new EventStore();
  
  var timer1 = timers.setInterval(()=&gt;{
      eventStore.insert(model, (err)=&gt;{
          if(err){
              console.log(err);
          }else{
              console.log("Test Completed!");
  
          }
      });
  }, 1000);
  
  var timer2 = timers.setInterval(()=&gt;{
      eventStore.insert(model2, (err)=&gt;{
          if(err){
              console.log(err);
          }else{
              console.log("Test Completed!");
  
          }
      });
  }, 1000);
  </code></pre>
  
  <p>This is a snippet of the output I get. Here, "Test Completed" is shown for the first instances, after that, I'm getting the duplicate errors.</p>
  
  <pre><code>counter : 1
  counter : 1
  Test Completed!
  Test Completed!
  counter : 2
  { MongoError: E11000 duplicate key error collection: admin.testRoom index: 
  _id_ dup key: { : ObjectId('59d5da14cedd6f28a5db8c93') }
  </code></pre>
  
  <p>Can anyone help me with this? Thank you in advance! </p>