无法使用单个HTTP帖子保存到多个集合

时间:2018-06-05 09:56:35

标签: node.js mongodb express mongoose

这里是网络开发的新手。很抱歉看到一个看似简单的问题,但是我用谷歌搜索了一个多星期而没有找到解决方案,所以请原谅。

我使用Node.js作为服务器端脚本,使用MongoDB作为数据库。我正在尝试使用单个HTTP post请求将数据保存到多个集合。在下面的代码中,我可以保存到IncidentHeader集合,但不能保存到EmployeeInformation集合。我遇到了这个错误:

  

“UnhandledPromiseRejectionWarning:错误:发送后无法设置标头。”

这一切都可能吗?

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

0 个答案:

没有答案