I got this helper function:
const Account = require('../models/account');
exports.sendInvites = (accountIds, invite, callback) => {
if (!accountIds) {
callback('No account ids provided', null, null);
return;
}
accountIds.forEach((id) => {
Account.findOneAndUpdate({_id: id}, {$push: {organisationInvites: invite}}, callback);
});
};
Then I have this route:
router.post('/organisations', auth.verifyToken, (req, res, next) => {
const organisation = new Organisation({
name: req.body.name,
email: req.body.email,
admins: [req.body.createdBy],
createdBy: req.body.createdBy
});
organisation.save((err, organisation) => {
if (err) {
return res.status(500).json({
error: err,
data: null
});
}
organisationUtils.sendInvites(req.body.invites, {
inviter: req.body.createdBy,
organisation: organisation._id
}, (err, account, response) => {
if (err) {
return res.status(500).json({
error: err,
data: null
});
}
res.json({
error: null,
data: organisation
});
});
});
});
I get a Error: Can't set headers after they are sent.
error for the
res.json({
error: null,
data: organisation
});
part but I can't understand why this is happening. I tried looking at the accepted answer here Error: Can't set headers after they are sent to the client, did some digging but couldn't find any specific reason still what's happening in my particular example above. Any ideas?