Hey I am trying to export a csv from node.js (pulling the data from mongodb). I already have the data being pulled and separated by commas and all, but now I am trying to figure out how to actually send it... I am sticking this code in my routes file. Any advice on how to take the array of data and send it to a user straight for download on request.
here is the code: (I attempted the the bottom part of the code the second function)
exports.downloadContacts = function(req, res) {
async.waterfall([
function(callback) {
var source = [];
Friend.find({userId: req.signedCookies.userid}, function(err, friends) {
if(err) {console.log('err with friends for download');
} else {
var userMap = {};
var friendIds = friends.map(function (user) {
userMap[user.friend_id] = user;
return user.friend_id;
});
console.log(friends);
User.find({_id: {$in: friendIds}}, function(err, users) {
if(err) {console.log(err);
} else {
for(var i = 0; i < users.length; i++) {
console.log('users')
//console.log(users[i]);
source.push(users[i].firstNameTrue, users[i].lastNameTrue, users[i].emailTrue, users[i].phone, users[i].emailList, users[i].phoneList)
}
console.log(source);
callback(null, source);
}
});
}
});
}
],
function(err, source) {
var result = [];
res.contentType('csv');
csv()
.from(source)
.on('data', function(data){
result.push(data.join());
})
.on('end', function(){
res.send(result.join('\n'));
});
});
};