【问题标题】:Does nodejs supports updating many collection in one router?nodejs 是否支持在一个路由器中更新多个集合?
【发布时间】:2019-01-05 11:42:08
【问题描述】:

我尝试在一个路由器中更新我的两个集合,但它一直给我错误:

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

【问题讨论】:

    标签: node.js mongodb mean-stack


    【解决方案1】:

    首先,我强烈建议您放弃回调并改用 Mongo 的 Promise 行为。除非您打算同时执行这两个请求,否则您将使用 Promise 来表达这一点:

    Bloodrequest.findOne({ _id:"..." }).then(bloodrequest => {
        bloodrequest.request_status = "claimed";
    })
    .then(() => Blooddonation.findOne({ _id:"..." }).then(blooddonation => {
        blooddonation.blood_group = "test";
    });
    

    第二,我猜你从你的例子中删减了一些代码;你实际上没有回应(使用res)。根据错误,我猜您试图在 both 的回调中设置 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.
    });
    

    【讨论】:

      【解决方案2】:

      你需要你想要在 api.js 中更新的集合模型

      在路由处理函数中,你需要相关集合之间的事务。你可以 fawn npm 让这更容易 https://www.npmjs.com/package/fawn

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-19
        • 2015-08-02
        相关资源
        最近更新 更多