0

A newbie in web development here. Sorry to bug you with a seemingly simple issue, but I have googled for more than a week and not found a solution, so pardon my asking.

I am using Node.js for server-side script and MongoDB for the database. I am trying to save data to multiple collections using a single HTTP post request. In the code below, I am able to save to the IncidentHeader collection but not to the EmployeeInformation collection. I am encountering this error:

"UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent."

Is this at all possible?

app.post('/create-incident', (req, res) => {
  const createIncidentNumber = () => {
    return (incNumRandom =
      'ITASiR-' +
      randomString.generate({
        length: 6,
        readable: true,
        charset: 'alphanumeric',
        capitalization: 'uppercase'
      }));
  };

  var status = 'New';
  var dateTimeCreated = new Date().getTime();
  var dateSubmitted = new Date();
  console.log(`POST incident number: ${incidentNumber}`);

  const incidentHeader = new models.IncidentHeader({
    incidentNumber: incidentNumber,
    status: status,
    dateTimeCreated: dateTimeCreated,
    dateSubmitted: dateSubmitted
  });

  incidentHeader
    .save()
    .then(() => {
      res.status(200).send(IncidentHeader);
      console.log('Saved to IncidentHeader.');
    })
    .catch(e => {
      return res.status(400).send(e);
      console.log('Unable to save to IncidentHeader.');
    });

  console.log(
    `req.body.EmployeeInformation: ${JSON.stringify(
      req.body.EmployeeInformation
    )}`
  );

  const employeeInformation = new models.EmployeeInformation(
    req.body.EmployeeInformation
  );
  console.log(`Employee information incident number: ${incidentNumber}`);

  employeeInformation
    .save()
    .then(() => {
      res.status(200).send(EmployeeInformation);
      console.log('Saved to EmployeeInformation.');
    })
    .catch(e => {
      return res.status(400).send(e);
      console.log('Unable to save to EmployeeInformation.');
    });
});
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
  • add ur post request here, i think you missed the header – Velusamy Venkatraman Jun 05 '18 at 10:00
  • 2
    So, first newbie lesson. Don't do `return res.status(400).send(e);` **twice** as you have. You can only do that **once**. Instead of separating the promise chains, continue them until they are both done. i.e `incidentHeader.save().then(() => employeeHeader.save().then(() => ` or Promise.all `Promise.all([incdentHeader.save(), employeeHeader.save()]).then(() => ...` – Neil Lunn Jun 05 '18 at 10:03

0 Answers0