猫鼬保存循环丢失迭代器

Mongoose save loop lost iterator

本文关键字:迭代器 循环 保存      更新时间:2023-09-26

我必须在我的数据库中保存大量的对象。

下面是我的代码示例:
for (var i = 0; i < userdata.length; i++) {
    var newCompany = Company({
      name: userdata[i].company_name
    });
    newCompany.save(function(err, c) {
        if (err) throw err;
        var newGeoloc = Geolocation({
            latitude: userdata[i].latitude,
            longitude: userdata[i].longitude
        });
        newGeoloc.save(function(err, g) {
            if (err) throw err;
        // Create new Office
        var newOffice = Office({
            name        : userdata[i].office_name,
            address     : userdata[i].address,
            city        : userdata[i].city,
            zip_code    : userdata[i].zip_code,
            geolocation : g._id,
            company     : c._id
        });
        // Save the Office
        newOffice.save(function(err, officeCreated) {
            if (err) throw err;
            console.log('Office created!');
        });
    });
}

为什么我的i变量当我保存地理位置对象latitude: datas[i].latitude得到我的数组userdata.length的最大长度?例如,如果userdata有150对象,我将总是得到150当我创建地理位置对象。

我该怎么办?

由于for循环运行时没有等待save函数接收回调,因此可以使用闭包将i的值保持为自调用函数的本地值,如下所示。

for (var i = 0; i < userdata.length; i++) {
    (
        function(index) {
            var newCompany = Company({
                name: userdata[index].company_name
            });
            newCompany.save(function(err, c) {
                if (err) throw err;
                var newGeoloc = Geolocation({
                    latitude: userdata[index].latitude,
                    longitude: userdata[index].longitude
                });
                newGeoloc.save(function(err, g) {
                    if (err) throw err;
                    var newOffice = Office({
                        name        : userdata[index].office_name,
                        address     : userdata[index].address,
                        city        : userdata[index].city,
                        zip_code    : userdata[index].zip_code,
                        geolocation : g._id,
                        company     : c._id
                    });
                    // Save the Office
                    newOffice.save(function(err, officeCreated) {
                        if (err) throw err;
                        console.log('Office created!');
                    });
                });
           });
        }
    )(i);
}

当每次循环运行时调用自调用函数时,i的值被复制到变量index