Skip to content

Instantly share code, notes, and snippets.

@aepyornis
Created January 15, 2015 22:31
Show Gist options
  • Save aepyornis/2341a13b2658b3c62b48 to your computer and use it in GitHub Desktop.
Save aepyornis/2341a13b2658b3c62b48 to your computer and use it in GitHub Desktop.
writeCSV
function writeCSV(columnNames, fileName, query, callback){
var db = mongojs('mongodb://localhost:27017/test', ['jobs']);
//array of columnNames
var columns = [];
//ensure that columnNames is array
if (typeof columnNames === 'string') {
columns.push(columnNames);
} else if (columnNames.constructor === Array) {
columns = columnNames;
} else {
console.log('columnNames is not a string or an array');
throw err;
}
//ensure query is object
if (typeof query !== 'object') {
query = {};
}
//create write stream
var file = fs.createWriteStream(fileName + '.csv');
//write headers
file.write(columns.join());
file.write('\n')
//create cursor
var cursor = db.jobs.find(query);
//listen for each document
cursor.on('data', function(doc){
//write fields for each document
columns.forEach(function(columnName, index, arr){
var field = '' + doc[columnName];
file.write(field);
//prevents trailing comma
if(index !== (arr.length - 1)) {
file.write(',');
}
})
//start new line
file.write('\n');
})
//functions to call when cursor is finished
cursor.on('end', function(){
//end write stream
file.end()
//close database
db.close();
//optional callback()
typeof callback === 'function' && callback();
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment