2

I am trying to write the results of 3 Mongoose find query into a single file test.txt using event-stream nodejs.

My program is something like this…

var es = require('event-stream');
var fs = require('fs');
var wstream = fs.createWriteStream('TestFile.csv');

mongoose.connection.on('connected', function () {  

//First Find Query
Model.find({"FirstId":{$exist:true}).cursor()
.pipe(es.map(function (data, callback) {

 var csv = json2csv({data:formated, fields:fields, hasCSVColumnTitle:false});
  callback(null, csv)
  }))
  .pipe(wstream);

//Second find query
Model.find({"SecondId":{$exist:true}).cursor()
.pipe(es.map(function (data, callback) {
if(data.Email)
{  
  var csv = json2csv({data:formated, fields:fields, hasCSVColumnTitle:false});
}
else{
callback();
}
  callback(null, csv)
}))
.pipe(wstream);


 //Third find query
 Model.find({"ThirdId":{$exist:true}).cursor()
 .pipe(es.map(function (data, callback) {
 if(data.Email)
 {  
  var csv = json2csv({data:formated, fields:fields, hasCSVColumnTitle:false});
 }
 else{
 callback();
 }
  callback(null, csv)
 }))
 .pipe(wstream);

  });

In this program I am able to write each find query result separately into the file. But when I combine 3-find query in a program, it throws “write after end” error.

Could anyone help me to resolve this error?

Thank You all for your time!

mvs
  • 33
  • 1
  • 8

0 Answers0