【问题标题】:Creating unique Mongoose objects from CSV从 CSV 创建唯一的 Mongoose 对象
【发布时间】:2015-06-18 23:30:55
【问题描述】:

假设我有一个 CSV,其中包含需要解析为不同 Mongoose 对象的信息。我需要根据 CSV 文件中的一些信息查找或创建“用户”。但是,如果我运行它,它每次都会创建一个新用户,因为它不会等到数据库保存完成后才执行 CSV 的其余部分。

fs.readFile(file, function(err, data) {
  if (err) throw err;
  parse(data, function(err, output) {
    if (err) throw err;

    User.findOne({name: output[0] }, function(err, user) {
      if (err) throw err;

      if (!user) {
        var user = new User({ name: output[0] });
        user.save(function(err, user) {
          anotherFunctionWithRestOfData(user, output);
        });
      } else {
        anotherFunctionWithRestOfData(output);
      }
    });
  })
})

我怎样才能控制这一点,以免重复数据被保存?

谢谢。

【问题讨论】:

    标签: javascript node.js mongodb csv mongoose


    【解决方案1】:

    您可以使用async's eachSeries 方法。

    我假设 output 是一个用户数组。 Async 的 eachSeries 将遍历一个数组,处理一个项目,一旦调用回调方法,就转到数组中的下一个项目:

    fs.readFile(file, function(err, data) {
        if (err) throw err;
        parse(data, function(err, output) {
            if (err) throw err;
    
            async.eachSeries(output, function(user, callback){
                // do your stuff with user
                // when it's done, go to the next one by calling callback
                callback(err);
            },function(err){
                // handle errors
            });
    
        })
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      • 2014-10-22
      • 1970-01-01
      • 2017-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多