Stream from a mongodb cursor to Express response in node.js

前端 未结 5 1206
死守一世寂寞
死守一世寂寞 2020-11-29 05:12

I am toying around with all the fancy node.js/mongodb/express platforms, and stumbled across a problem:

app.get(\'/tag/:tag\', function(req, res){
  var tag=         


        
5条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 06:00

    A working combination of other answers here

    app.get('/comments', (req, res) => {
      Comment.find()
        .cursor()
        .pipe(JSONStream.stringify())
        .pipe(res.type('json'))
    })
    

    http://mongoosejs.com/docs/api.html#query_Query-cursor

    • cursor() returns a Node streams3 compatible stream and is preferred over the deprecated query.stream() interface.
    • Piping to JSONStream.stringify() to combine documents into an array instead of single objects
    • Piping to res.type('json') which sets the HTTP Content-Type header to application/json and returns itself (the response stream) again.

提交回复
热议问题