MongoSkin错误的插入

我有一个与以下结构的国家arrays:

{ "code": "ZW", "name": "Zimbabwe", "zipPattern": "[\\s\\S]*", "states": [ { "name": "Bulawayo" }, { "name": "Harare" }, { "name": "Manicaland" }, { "name": "Mashonaland Central" }, { "name": "Mashonaland East" }, { "name": "Mashonaland West" }, { "name": "Masvingo" }, { "name": "Matabeleland North" }, { "name": "Matabeleland South" }, { "name": "Midlands" } ] } 

我想用下面的代码使用MongoSkin将它们插入到MongoDb

 var countries = require('./mongo/ready/Countries'); db.collection('countries').find().toArray(function (err, result) { if (result.length === 0) { for (var i = 0; i < countries.length; i++) { var obj = countries[i]; var states = obj.states; db.collection('countries').insert({ name: obj.name, code: obj.code, zipPattern: obj.zipPattern }, function (error, countryResult) { var id = countryResult[0]._id; for (var j = 0; j < states.length; j++) { var state = states[j]; db.collection('states').insert({ countryId: id, name: state.name }, function (stateError, stateResult) { if (stateError) console.log(stateError); console.log(stateResult); }); } }); } } }); 

但是代码插入数组中的最后一个国家(津巴布韦)的状态为arrays中的每个国家,而不是正确的状态。 我该如何解决?

通常我们不使用同步循环(simple for loop)之间的asynchronous查询(插入)。 它给了我们无与伦比的结果。 节点提供asynchronous循环来克服这一点。

首先为此需要asynchronous模块。

 var async = require('async'); 

现在你可以使用下面的代码来插入国家和他们各自的国家

 async.each(countries, function(obj, callback) { var states = obj.states; db.collection('countries').insert({ name: obj.name, code: obj.code, zipPattern: obj.zipPattern }, function(error, countryResult) { if (error) { callback(error); } else { var id = countryResult[0]._id; async.each(states, function(state, callback) { db.collection('states').insert({ countryId: id, name: state.name }, function(stateError, stateResult) { if (stateError) { callback(stateError); } else { callback(); } }); }); callback(); } }); }, function(err) { if (err) { // handle error here } else { // do stuff on completion of insertion } }); 

谢谢