Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

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

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=req.params.tag;
  console.log('got tag ' + tag + '.');
  catalog.byTag(tag,function(err,cursor) {
     if(err) {
       console.dir(err);
       res.end(err);
     } else {
       res.writeHead(200, { 'Content-Type': 'application/json'});

       //this crashes
       cursor.stream().pipe(res);

     }
  });
});

As you probably guessed, catalog.byTag(tag, callback) does a find() query to Mongodb and returns the cursor

This leads to an error:

TypeError: first argument must be a string or Buffer

According to mongodb driver doc, I tried to pass this converter to stream():

function(obj) {return JSON.stringify(obj);}

but that does not help.

Can anybody tell me how to correctly stream something to a response?

Or is the only solution a boilerplate to manually pump the data using the 'data' and 'end' events?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the cursor stream in combination with JSONStream to pipe it to your response object.

cursor.stream().pipe(JSONStream.stringify()).pipe(res);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...