0

I have an array and I want to insert the data inside mongodb.

This is my current code:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/xyz')

var countrySchema = mongoose.Schema({
  countryName {
    countryCode: String,
    Regions: {
      regionName: {
        regionCode: String
      }
    }
  }
});
// schema doesn't seem to matter.
var Country = mongoose.model('Country', countrySchema)

    var foo = [["Afghanistan","AF","Badakhshan~BDS|Badghis~BDG|Baghlan~BGL|Balkh~BAL|Bamyan~BAM|Daykundi~DAY|Farah~FRA|Faryab~FYB|Ghazni~GHA|Ghor~GHO|Helmand~HEL|Herat~HER|Jowzjan~JOW|Kabul~KAB|Kandahar~KAN|Kapisa~KAP|Khost~KHO|Kunar~KNR|Kunduz~KDZ|Laghman~LAG|Logar~LOW|Maidan Wardak~WAR|Nangarhar~NAN|Nimruz~NIM|Nuristan~NUR|Paktia~PIA|Paktika~PKA|Panjshir~PAN|Parwan~PAR|Samangan~SAM|Sar-e Pol~SAR|Takhar~TAK|Urozgan~ORU|Zabul~ZAB"]];
     // foo is just a small sample, it's only the first element of the complete array.


var countriesArray = foo.map(function(value) {
  var country = {};
  value[0] = value[0].replace(/\./gi, '')
  value[1] = value[1].replace(/\./gi, '')
  value[2] = value[2].replace(/\./gi, '')

  country[value[0]] = {
    countryCode: value[1],
    Regions: {}
  }
  if (value[2].match(/\|/gi)) {
    value[2].split('|').map(function(currentRegion) {
      var regionSplit = currentRegion.split('~');
      country[value[0]].Regions[regionSplit[0]] = {
        regionCode: regionSplit[1]
      }
    })
  } else if (value[2].match(/\~/gi)) {
    var regionSplit = value[2].split('~');
    country[value[0]].Regions[regionSplit[0]] = {
      regionCode: regionSplit[1]
    }
  } else {
    country[value[0]].Regions[value[2]] = {
      regionCode: 'Missing'
    }
  }
  return country;
})


Country.collection.insert(countriesArray, function(err, countriesArray) {
  if (err) {
    console.log(err)
  } else {
    console.log('Done')
  }
});

Obviously this does not work as I would like it, it only inserts the info from the last region since newCountry.save() is called after the loop is finished. What would be the best method do achieve inserting all the regions to their own countries?

PS I only need this to happen once so memory usage,speed and other things like that do not matter.

Trax
  • 1,445
  • 5
  • 19
  • 39
  • 1
    You are looking for a batch insert as described [here](http://stackoverflow.com/questions/16726330/mongoose-mongodb-batch-insert). – domyos May 22 '16 at 12:27

1 Answers1

1

To do a batch insert you first must create an array of Objects you want to insert. For this you can do a map on the foo Array and then insert this array in one step. Here's some example code:

var Country =  mongoose.model('Country', countrySchema);    

var countries = foo.map(function(value) {
  var country = {};
  // do something with your array.
  return country;
}

Country.collection.insert(countries, function(err, countries) {
  console.log('Inserted ', countries.length, ' documents.');
});
domyos
  • 153
  • 1
  • 9