title: How to insert array to mongodb using node.js
body: <p>I have an array like <code>[ 570dec75cf30bf4c09679deb, 56fe44836ce2226431f5388f ]</code>. Now I want insert this for new collection named <code>notifications</code> like </p>
  
  <pre><code>{
    "_id": ObjectId("57bd39c9734ff3602a312b33"),
    "userId": ObjectId("570dec75cf30bf4c09679deb") 
  }
  
  and
  
  {
    "_id": ObjectId("57bd39c8734ff3602a312b32"),
    "userId": ObjectId("56fe44836ce2226431f5388f ") 
  }
  </code></pre>
  
  <p>I have written a query in node.js to insert this but it inserting last element of array two times like this</p>
  
  <pre><code>{
    "_id": ObjectId("57bd39c9734ff3602a312b33"),
    "userId": ObjectId("56fe44836ce2226431f5388f ") 
  }
  
  and
  
  {
    "_id": ObjectId("57bd39c8734ff3602a312b32"),
    "userId": ObjectId("56fe44836ce2226431f5388f ") 
  }
  </code></pre>
  
  <p>The query I have written like this</p>
  
  <h2>app.js</h2>
  
  <pre><code>router.post('/creatList', function(req,res){
      console.log(req.body.email);
      var emails = req.body.email;
  
      if(req.body.wData.wishListType == 'Shared'){
          var findUsers = function(db, callback) {
              var cursor;
              cursor = db.collection('users').find({email: { $in: emails }})
  
              cursor.toArray(function(err, docs){
                  if(err){
                      callback(new Error("Some problem"));
                  } else {
                      callback(null,docs);
                  } 
              });     
          };
  
          MongoClient.connect(config.database, function(err, db) {
              assert.equal(null, err);
              findUsers(db, function(err,docs) {
                  db.close();
                  console.log(docs);
  
                  for(var key in docs){
                      console.log(key);
                      var ids = docs[key]._id;
                      console.log(ids);
  
                      var insertDocument = function(db, callback) {
                          db.collection('notifications').insert({
                              "userId" : ids,
                          },function(err, result) {
                              assert.equal(err, null);
                              console.log("Inserted a document into the notifications collection.");
                              callback();
                          });
                      };
  
                      MongoClient.connect(config.database, function(err, db) {
                          assert.equal(null, err);
                          insertDocument(db, function() {
                              db.close();
                          });
                      });
                  }
              });
          }); 
        });
  </code></pre>