MongoSkin插错了

时间:2015-03-16 11:40:29

标签: node.js mongodb mongoskin

我有一个包含以下结构的国家/地区的数组:

{
    "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"
        }
    ]
}

我正在尝试使用以下代码

MongoDb插入MongoSkin
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);
                });
            }
        });
    }
  }
});

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

1 个答案:

答案 0 :(得分:1)

通常我们不在同步循环(简单循环)之间使用异步查询(插入)。它给了我们非常好的结果。 Node提供异步循环来克服这个问题。

首先需要异步模块。

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

由于