복붙노트

[MONGODB] Node.js를 익스프레스 응답에 MongoDB를 커서에서 스트림

MONGODB

Node.js를 익스프레스 응답에 MongoDB를 커서에서 스트림

나는 모든 멋진 Node.js를 / MongoDB를 / 급행 플랫폼과 주위 놀겠다는 거, 그리고 문제를 우연히 발견하고 있습니다 :

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

     }
  });
});

당신은 아마 짐작으로 catalog.byTag (태그, 콜백) MongoDB를에 발견 () 쿼리를 수행하고 커서를 반환

오류이 리드 :

TypeError: first argument must be a string or Buffer

드라이버 문서를 MongoDB를에 따르면, 나는 () 스트림이 변환기를 통과했습니다 :

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

하지만 도움이되지 않습니다.

사람이 어떻게 반응 올바르게 스트림 뭔가 말해 줄 수 있습니까?

또는 유일한 해결책은 '데이터'와 '끝'이벤트를 사용하여 데이터를 펌프를 수동으로 보일러입니까?

해결법

  1. ==============================

    1.여기에 다른 답변의 작업 조합

    여기에 다른 답변의 작업 조합

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

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

  2. ==============================

    2.응답 객체에 파이프 그것을 JSONStream와 함께 커서 스트림을 사용합니다.

    응답 객체에 파이프 그것을 JSONStream와 함께 커서 스트림을 사용합니다.

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

    3.단순한. ({변환 : JSON.stringify를}) .stream;

    단순한. ({변환 : JSON.stringify를}) .stream;

  4. ==============================

    4.내 몽고 스트림은 스트링 또는 버퍼를 처리 할 수있는 고해상도 스트림 (따라서 에러), 물체를 덤핑된다.

    내 몽고 스트림은 스트링 또는 버퍼를 처리 할 수있는 고해상도 스트림 (따라서 에러), 물체를 덤핑된다.

    다행히, 스트림은 함께 파이프에 쉽게 데이터를 캐릭터 라인 화하는 변환 스트림을 만들기 위해 너무 너무 열심히하지 않습니다.

    잉꼬 때문에 v0.10.21 :

    var util = require('util')
    var stream = require('stream')
    var Transform = stream.Transform
    
    util.inherits(Stringer, Transform)
    
    function Stringer() {
      Transform.call(this, { objectMode: true } )
      // 'object mode allows us to consume one object at a time
    
    }
    
    Stringer.prototype._transform = function(chunk, encoding, cb) {
      var pretty = JSON.stringify(chunk, null, 2) 
      this.push(pretty) // 'push' method sends data down the pike.
      cb() // callback tells the incoming stream we're done processing 
    }
    
    var ss = new Stringer()
    
    db.createObjectStreamSomehow()
      .pipe(ss)
      .pipe(res)
    

    희망이 도움이

  5. ==============================

    5.몽구스 사용 및 표현 :

    몽구스 사용 및 표현 :

    function(req, res){
        var stream = database.tracks.find({}).stream();
        stream.on('data', function (doc) {
            res.write(JSON.stringify(doc));
        });
        stream.on('end', function() {
            res.end();
        });
    }
    
  6. from https://stackoverflow.com/questions/20058614/stream-from-a-mongodb-cursor-to-express-response-in-node-js by cc-by-sa and MIT license