Handle mongodb error when streaming directly to express response
WriteStream is ended when ReadStream ends or has an error.
So you need to somehow prevent this default behaviour when errors happen during pipe. You can do that by passing {end: false}
as pipe option.
This option alters default behavior so that even if the error occurs, your write stream is still open and you can keep sending more data down (e.g. error status).
var stream = cursor.stream();stream.on('error', function () { res.status(500).send(err.message);});stream.on('end', function(){ //Pipe does not end the stream automatically for you now //You have to end it manually res.end(); });stream.pipe(res, {end:false}); //Prevent default behaviour
More information can be found on:
https://nodejs.org/dist/latest-v6.x/docs/api/stream.html#stream_readable_pipe_destination_options