我有很多 .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()

最佳答案

如果没有看到实际代码很难说,但是尝试使用 fs.readFileSync 或者,最好对循环使用 async.each 或 async.auto,以便外循环在执行内循环之前实际完成。

关于mysql - 如何向 Sequelize 模型添加大量数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16765360/

10-09 21:10