我必须用 Mongoose 在数据库中保存很多对象。
这是我的代码示例:
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
的值code> 位于自调用函数的本地,如下所示。
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
中。
关于javascript - Mongoose 保存循环丢失迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39536478/