2016-05-22 91 views
0

我有一個數組,我想在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我只需要這樣的事情發生一次,所以內存的使用,速度和其他類似的事情並不重要。

+1

你正在尋找一個批量插入爲[這裏]描述(http://stackoverflow.com/questions/16726330/mongoose-mongodb-batch-insert)。 – domyos

回答

1

要進行批量插入,首先必須創建一個要插入的對象數組。爲此,您可以在foo Array上執行映射,然後在一個步驟中插入此數組。 下面是一些示例代碼:

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

這非常感謝。 – Trax