我试图在一台路由器上更新两个集合,但是它一直给我错误:
Error: Can't set headers after they are sent. at validateHeader (_http_outgoing.js:494:11) at ServerResponse.setHeader (_http_outgoing.js:501:3)
这是我所做的:
api.js
router.put('/editbloodrequest', function(req, res) {
//this works
Bloodrequest.findOne({ _id:"5c1d2c8c68503b0adceffa92"}, function(err, bloodrequest) {
if (err) throw err;
bloodrequest.request_status = "claimed";
});
//but after inserting this, it gives me error
Blooddonation.findOne({ _id:"5c00fa03dadb0c3b00739dd9"}, function(err, blooddonation) {
if (err) throw err;
blooddonation.blood_group = "test";
});
});
答案 0 :(得分:1)
首先,我强烈建议您放弃回调,而改用Mongo的 Promise 行为。除非您打算同时执行两个请求,否则这将是您使用promises表示的方式:
Bloodrequest.findOne({ _id:"..." }).then(bloodrequest => {
bloodrequest.request_status = "claimed";
})
.then(() => Blooddonation.findOne({ _id:"..." }).then(blooddonation => {
blooddonation.blood_group = "test";
});
第二,我猜您从示例中删除了一些代码;您实际上没有反应(使用res
)。基于该错误,我猜测您尝试在回调的两者中设置res
。您只能响应一次,该错误通常意味着您已经重定向/响应了等等,现在正尝试再次尝试。
通常,您会这样做:
Bloodrequest.findOne({ _id:"..." }).then(bloodrequest => {
bloodrequest.request_status = "claimed";
})
.then(() => Blooddonation.findOne({ _id:"..." }).then(blooddonation => {
blooddonation.blood_group = "test";
}).then(() => {
// set your positive res response
}).catch(error => {
// set your error res response
// since you're using promises, if any of the above steps fail, you'll
// end up here.
});
答案 1 :(得分:0)
您需要需要在api.js中更新的集合模型
在路由处理程序功能中,您需要在相关集合之间进行事务处理。您可以小鹿npm 来简化此操作 https://www.npmjs.com/package/fawn