假设我有一个包含需要解析为不同Mongoose对象的信息的CSV。我需要根据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);
}
});
})
})
如何控制它以便不保存重复数据?
感谢。
答案 0 :(得分:1)
您可以使用async's eachSeries方法。
我假设输出是一组用户。 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
});
})
})