Piping mongoose document to Node.js response stream


You can keep the mongoose documents as streams by calling cursor() and piping directly to the response stream of the HTTP server. In this example I’m using it in an Express.js router route definition. Since Node.js streams expect stream data to be of type String or Buffer, the JavaScript object needs to be stringified first using a transform function. JSON.stringify can be used directly which helps in making this a nice pipeline.

router.get('/', (req, res, next) => {
    .cursor({transform: JSON.stringify})