【问题标题】:Mongoose batch insert to sub-categoryMongoose 批量插入子类别
【发布时间】:2016-09-19 08:14:54
【问题描述】:

我有一个数组,我想在 mongodb 中插入数据。

这是我当前的代码:

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')
  }
});

显然这并不像我想要的那样工作,它只插入来自最后一个区域的信息,因为在循环完成后调用 newCountry.save()。将所有地区插入自己的国家/地区的最佳方法是什么?

PS 我只需要这种情况发生一次,所以内存使用、速度和其他类似的事情都无关紧要。

【问题讨论】:

  • 您正在寻找如here 所述的批量插入。

标签: javascript node.js mongodb mongoose


【解决方案1】:

要进行批量插入,您首先必须创建一个要插入的对象数组。为此,您可以在 foo 数组上进行映射,然后一步插入该数组。 下面是一些示例代码:

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.');
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-03
    • 2016-09-19
    • 2015-10-20
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多