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.');
});
});