我有许多 .txt 文件,其中每一行都有一些我想添加到模型中的数据,以便可以进行查询。问题是没有执行任何“插入”查询,这可能是由于库的异步性。
这是我所拥有的:
// Connect to DB
// Set up Model
// Model.sync()
// first for loop (for each .txt)
// second for loop (nested) (for each line in the .txt)
// in second for loop: Model.create(data);
我该怎么做才能确保每个数据对象都成功添加到数据库中?
这是代码:
var Location = sequelize.define('Location', {
name: Sequelize.STRING,
country: Sequelize.STRING,
lat: Sequelize.STRING,
long: Sequelize.STRING
});
Location.sync().success(function(){
for (var i = 0; i < txts.length; i++){
var txt = txts[i],
country = txt.substr(0, txt.indexOf('.')),
data = fs.readFileSync(dir +"/" + txt, 'utf-8'),
locations = data.split('\n');
for (var j =1; j < locations.length; j++){
var loc = locations[j],
chunks = _.without(loc.split('\t'), ''),
lat = chunks[3],
long = chunks[4],
name = chunks[16]
Location.build({
country: country,
lat: lat,
long: long,
name: name
})
.save()
.success(function(){
console.log('success');
})
.error(function(err){
if (err) throw err;
});
}
}
我尝试使用 lodash 的 forEach 方法来遍历循环,但两种方法似乎都跳过了 Location.build()