NodeJS / MongoDB – 错误:发送后无法设置标头

我有这个帮手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); }); }; 

那么我有这条路线:

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

我得到一个Error: Can't set headers after they are sent. 错误的

 res.json({ error: null, data: organisation }); 

部分,但我不明白为什么发生这种情况。 我试着看在这里接受的答案错误:发送到客户端后 , 无法设置标题 ,做了一些挖掘,但找不到任何具体的原因,仍然发生在我上面的特定示例中。 有任何想法吗?

您多次调用callback,所以res.json多次。 从所有数据库请求收集数据,然后执行一个独特的res.json

 accountIds.forEach((id) => { Account.findOneAndUpdate( {_id: id}, {$push: {organisationInvites: invite}}, callback, ); }); 

就像是 :

  var allData = []; var nbRequestDone = 0; var waitAllCallback = function (data, err) { if (err) { callback(err); nbRequestDone = accountIds.length; return; } nbRequestDone += 1; allData.push(data); if (nbRequestDone === accountIds.length) { callback(false, allData); } }; accountIds.forEach((id) => { Account.findOneAndUpdate(..., waitAllCallback); });