从mongodb游标流到node.js中的Express响应 [英] Stream from a mongodb cursor to Express response in node.js

查看:121
本文介绍了从mongodb游标流到node.js中的Express响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩所有的花絮node.js / mongodb / express平台,偶然遇到一个问题:

  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'});

//这会崩溃
游标。 stream()。pipe(res);

}
});
});你可能猜到, catalog.byTag(tag,callback) code>对Mongodb执行 find()查询并返回光标



这会导致错误:

  TypeError:第一个参数必须是一个字符串或缓冲区

根据 mongodb driver doc
我试图将此转换器传递给 stream()

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

没有帮助。



有人可以告诉我如何正确地流式传输一些响应?



或是唯一的解决方案是使用数据和结束事件手动泵送数据的样板?

解决方案

其他答案在这里

  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()返回一个Node streams3兼容流,优先于不推荐使用的 query.stream ()界面。

  • 将<文件>单个对象

  • 管道到 res.type('json')它设置HTTP Content-Type 头到 application / json 并再次返回自己(响应流)。


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?

解决方案

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.

这篇关于从mongodb游标流到node.js中的Express响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆