title: I am trying to iterate through an array of ids and insert a mongodb document if an id is not present. How can i get them to persist?
body: <p>I am working with Node JS and mongodb and I have a collection of documents with ids from 1-5000. However there are some ids that are missing and I want each document to have one ID.</p>
  
  <p>Here is the code I'm working with:</p>
  
  <pre><code>MongoClient.connect("mongodb://localhost:27017/test", function(err, db) {
      if(err) {
          console.log("Unable to connect", err);
          return;
      } 
  
      console.log("We are connected");
  
      var collection = db.collection('examples');
  
      collection.aggregate(
          [
              {"$sort": {"user_id": 1} },
              {"$out": "users"}
          ]
      ).toArray(function(err, docs) {
          var toSave = [];
          db.collection('users').find().toArray(function(err, docs){
              docs.forEach(function(doc){
                  toSave.push(doc.user_id);
              })
  
              for (var i = 1; i &lt; 5000; i++) {
  
                  if (toSave.indexOf(i) == -1) {
                      db.collection('examples').insert({
                          user_id: i,
                          create_dt: new Date()
                      })
                  }
              }
  
              console.log(toSave);
              db.close()
          })
      });
  });
  </code></pre>
  
  <p>I was hoping this would go through my toSave array and insert documents for each of the missing user_id's but when I check my database it only ever creates one document. </p>
  
  <p>How can I get all of the documents to save in the database?</p>