2017-12-18 168 views
2

我試圖讓我從我的neo4j數據庫中保存idsFromMongo並搜索mongodb中的這些id以返回我想要的對象。它工作1次,但然後我的服務器崩潰,並返回錯誤發送後無法設置標題。他們設置後不能設置標題

這是我的代碼:

routes.get('/advertisements/recommended/:brand', function(req, res) { 
    res.contentType('application/json'); 

    var brandFromUrl = req.params.brand; 
    var advertisementIds = []; 

    Advertisement.find({'car.brand': brandFromUrl}) 
    .then(function (ads) { 
     // res.status(200).json(ads); 
     ads.forEach(function (record) { 
     console.log('ids: ' + record._id) 
     session 
      .run("MERGE(a:Advertisement {idFromMongo: {idParam}, brand: {brandParam}}) WITH a MATCH(b: Advertisement {brand: {brandParam}}) MERGE(a)-[:SHARED_BRAND]->(b)", {idParam: record._id.toString(), brandParam: brandFromUrl}) 
      .then(function(result) { 
      session 
       .run("MATCH (n:Advertisement{brand: {brandParam}}) RETURN (n)", {brandParam: brandFromUrl}) 
       .then(function(result) { 
       result.records.forEach(function(record){ 
        advertisementIds.push(record._fields[0].properties.idFromMongo); 
       }); 
       Advertisement.find({ 
        '_id': { $in: advertisementIds} 
       }, function(err, docs){ 
        res.status(200).json(docs); 
       }) 
      }) 
     }) 
     }); 
    }) 
    .catch((error) => { 
     res.status(400).json(error); 
    }); 
}); 

這是我的錯誤:

Error: Can't set headers after they are sent. 
    at validateHeader (_http_outgoing.js:494:11) 
    at ServerResponse.setHeader (_http_outgoing.js:501:3) 
    at ServerResponse.header (c:\dev\individueel-project\individueel-database\node_modules\express\lib\response.js:767:10) 
    at ServerResponse.send (c:\dev\individueel-project\individueel-database\node_modules\express\lib\response.js:170:12) 
    at ServerResponse.json (c:\dev\individueel-project\individueel-database\node_modules\express\lib\response.js:267:15) 
    at c:\dev\individueel-project\individueel-database\api\advertisement.routes.v1.js:70:35 
    at model.Query.<anonymous> (c:\dev\individueel-project\individueel-database\node_modules\mongoose\lib\model.js:4046:16) 
    at c:\dev\individueel-project\individueel-database\node_modules\kareem\index.js:273:21 
    at c:\dev\individueel-project\individueel-database\node_modules\kareem\index.js:131:16 
    at _combinedTickCallback (internal/process/next_tick.js:131:7) 
    at process._tickCallback (internal/process/next_tick.js:180:9) 
+0

每個請求只能發送一次回覆。但是在你的代碼中,你正在發送多個響應來進行聲明 – ZeroCho

回答

0

這裏的問題是,你正在執行一個數組,並放入數組您發送的響應。所以,最終它會多次發送回覆,但只有第一次纔會起作用,之後會引發錯誤。 爲了解決這個問題,你應該在數組中的所有承諾完成之後回答請求(Promise.all),或者如果你不需要等到整個數組完成,那麼檢查你是否已經做出了迴應並且不做它再次。