Wednesday 17 May 2017

Keep getting Error: Can't set headers after they are sent

So I am trying out my code for updating and showing it to the user. Basically it is able to do what I need to do but after performing it I get this error

C:\Users\tester01_2\myproject\node_modules\mongodb-core\lib\cursor.js:174
  throw err;
  ^

Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:357:11)
at ServerResponse.header ( 
C:\Users\tester01_2\myproject\node_modules\express\lib\response.js:725:10)
at ServerResponse.send 
(C:\Users\tester01_2\myproject\node_modules\express\lib\response.js:170:12)
at C:\Users\tester01_2\myproject\dbUpdate.js:13:14
at C:\Users\tester01_2\myproject\dbUpdate.js:28:5
at handleCallback (C:\Users\tester01_2\myproject\node_modules\mongodb-
core\lib\cursor.js:171:5)
at nextFunction (C:\Users\tester01_2\myproject\node_modules\mongodb-
core\lib\cursor.js:682:5)
at Cursor.next [as _next] 
(C:\Users\tester01_2\myproject\node_modules\mongodb-
core\lib\cursor.js:692:3)
at loop 
(C:\Users\tester01_2\myproject\node_modules\mongodb\lib\cursor.js:694:8)
at _each 
(C:\Users\tester01_2\myproject\node_modules\mongodb\lib\cursor.js:741:16)

This is my code.

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var url = 'mongodb://localhost:27017/myproject';

module.exports = {

postCollection : function(req, res){
    var issueQty = req.body.issueQty;
    var itemDescrip = req.body.itemDescrip;
MongoClient.connect(url, function(err, db) {
    assert.equal(null, err);
    updateRecord(db, req, function(doc) {
    return res.send('Record Found. Now updating this document...' + 
itemDescrip + ' Record Updated. This is the new record ' + doc )
    res.end();
    db.close();
    });

});
}
}
var updateRecord = function(db, req, callback) {
var cursor = db.collection('documents').find({'Item Description': 
req.body.itemDescrip, 'Issued QTY': req.body.issueQty})
cursor.each(function(err,doc){
   assert.equal(err, null);
     if(doc != err){
         console.log('Successfully queried');
         console.log(doc);
         callback(JSON.stringify(doc));

     } else{
         throw err;
     }
  });
db.collection('documents').updateMany(
  { 'Item Description': req.body.itemDescrip},
  {
    $set: { 'Issued QTY': req.body.issueQty }
  },function(err, results) {
    console.log(results);
    console.log('Done');
    console.log(results);

});
};

I think it has to do with my res due to all the threads I have seen being res being in a wrong position but I need to put my res.send there so that it can use doc. Is there any way to solve this problem? Thanks.



via Ong Kong Tat

No comments:

Post a Comment