2014-09-22 96 views
0

我使用express,mongoose和async。異步瀑布回調沒有在貓鼬內部調用保存

在一個控制器上的更新方法,我打電話以下幾點:

//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方法的回調是異步的,那麼爲什麼這似乎工作?

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 2014-09-22 18:15:35

+0

有人可以提供工作代碼嗎? – nottinhill 2015-10-06 14:31:00