2014-09-22 2 views
0

express, mongoose 및 async를 사용하고 있습니다.mongoose save 내에서 async waterfall 콜백이 호출되지 않습니다.

//note: we're within a constructor's prototype method, hence the 'self'. also body is simply the request body. 

    async.waterfall([ 
     function(callback) { 
      self.collection.findById(body._id).exec(function(err, item) { 
       if(item) { 
        callback(null, item); 
       } else { 
        callback(err); 
       } 
      }); 
     }, 
     function(item, callback) { 
      //callback(null, item); //makes this task work, but not what I need 

      //merge two together models together, then save 
      item.save(_.extend(item, body), function(err, item) { 
       console.log('code here never seems to get called within the waterfall'); 
       callback(null, item); 
      }); 
     } 
    ], function(err, results) { 
     console.log('hello', err, results); 
     self.res.json(results); 
    }); 

을 그래서 기본적으로 내가 할 노력하고있어하는 ID로 문서를 찾을 것입니다, 다음에 새 개체를 병합 : 컨트롤러에 업데이트 방법 내에서

, 나는 다음과 같은 전화 드렸습니다 하나는 방금 발견, 그것을 저장하고 결과를 JSON으로 반환합니다. 그러나 .save 내에 중첩 된 콜백 함수는 결코 호출되지 않습니다. 따라서 전체 요청이 중단 된 것처럼 보이며 폭포의 마지막 기능이 호출되지 않습니다.

내가 틀렸을 수도 있지만 save 메소드의 콜백이 비동기 적으로 호출되는 것 같습니다. 어떻게이 일이 가능해질까요?

사이드 노트 : save 메소드의 콜백이 async이면, 이것이 왜 작동하는 것입니까?

var _this = this; 
    var item = new this.collection(this.req.body); 
    item.save(function(err, data) { 
     _this.res.json(data); 
    }); 

이 메서드는 저장된 개체를 JSON으로 반환합니다.

답변

2

Model.save 메서드를 올바르게 사용하고 있지 않습니다. 첫 번째 인수로 콜백 만 걸립니다. item 인스턴스를 가져온 다음 item 인스턴스에서 새 속성 값을 설정 한 다음 item.save(callback);을 수행해야합니다.

+0

감사합니다. 내가 그걸 잡지 못하는 것은 어리 석다. – ccnokes

+0

누군가 작업 코드를 제공 할 수 있습니까? – nottinhill

관련 문제