title: process.nextTick(function() { throw err; }); Error: Can't set headers after they are sent
body: <p>I'm trying get data from MongoDB in a Node.js file.<br />
  I'm getting this error:</p>
  <blockquote>
  <p>/home/jay/node_project/user_data_manag/node_modules/mongodb/lib/utils.js:98<br />
  process.nextTick(function() { throw err; });</p>
  <p>Error: Can't set headers after they are sent.<br />
  at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)<br />
  at ServerResponse.header (/home/jay/node_project/user_data_manag/node_modules/express/lib/response.js:719:10)<br />
  at ServerResponse.json (/home/jay/node_project/user_data_manag/node_modules/express/lib/response.js:247:10)<br />
  at ServerResponse.send (/home/jay/node_project/user_data_manag/node_modules/express/lib/response.js:152:21)<br />
  at /home/jay/node_project/user_data_manag/routes/api.js:42:13<br />
  at /home/jay/node_project/user_data_manag/node_modules/mongodb/lib/cursor.js:777:7<br />
  at handleCallback (/home/jay/node_project/user_data_manag/node_modules/mongodb/lib/utils.js:96:12)<br />
  at /home/jay/node_project/user_data_manag/node_modules/mongodb/lib/cursor.js:741:16<br />
  at handleCallback (/home/jay/node_project/user_data_manag/node_modules/mongodb/lib/utils.js:96:12)<br />
  at /home/jay/node_project/user_data_manag/node_modules/mongodb/lib/cursor.js:675:5</p>
  </blockquote>
  <pre class="lang-js prettyprint-override"><code>// Dependencies
  var express = require('express');
  var router = express.Router();
  var mongo = require('mongodb').MongoClient;
  var objectId = require('mongodb').ObjectID;
  var assert = require('assert');
  
  var url = 'mongodb://localhost/rest_test';
  
  
  router.post('/user', function(req, res, next) {
    if (req.body.name == &quot;Login&quot;) {
      var result = [];
      mongo.connect(url, function(err, db) {
        var data = db.collection('products').find();
        data.forEach(function(doc, err) {
          result.push(doc);
        }, function() {
          db.close();
          res.send({
            iteamd: result
          });
        });
      });
    } else {
      res.send(&quot;data&quot;);
    }
    res.end();
  });
  
  //insert data
  router.post('/put-data', function(req, res, next) {
  
    var item = {
      title: req.body.name,
      content: req.body.sku,
      author: req.body.price
    };
    var data = req.body.name;
  
    mongo.connect(url, function(err, db) {
      var cursor = db.collection('products').find({
        &quot;name&quot;: data
      });
      res.send(cursor.toString);
    });
  
  });
  
  
  // Return router
  module.exports = router;
  </code></pre>