Piping mongoose document to Node.js response stream

Revision history
Tags: mongoose mongodb express javascript node.js

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) => {
  Model.find()
    .cursor({transform: JSON.stringify})
    .pipe(res.type('json'))
})

References

If you have any comments or feedback, please send me an e-mail. (stig at stigok dotcom).

Did you find any typos, incorrect information, or have something to add? Then please propose a change to this post.

Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.