错误:发送后无法设置标头。在ServerResponse.OutgoingMessage.setHeader(_http_outgoing.js:356:11)中

问题描述 投票:0回答:2

由于错误,我正面临问题

发送后无法设置标头

实际上,我正在查询我的MongoDB。

Test.aggregate([
                {$match: {'ownerid': req.body.ownerid}},
                {$unwind: '$groupname'},
                {$project: {_id:1, groupname :"$groupname",}}
            ], function(error, data){
                if(error) {
                    console.log(error);
                } else {
                    //It will return Two group id.
                    for(var i=0; i<data.length; i++){

                        //These are the variables for my custom function which can update my query on another table
                        var primaryfilter = {'userid': req.body.ownerid};
                        var secondaryfilter = { "groupowned" : { 'groupid': data[i]._id, 'groupname': data[i].groupname } };
                        var activityname = 'Group Owned';
                        updater(req, res, Test1, primaryfilter, secondaryfilter, activityname);
                    }
                }
            });

这一个是我的更新程序功能:

var updater = function(req, res, CollectionName, primaryfilter, secondaryfilter, activityname){
    CollectionName.update(primaryfilter, {$push: secondaryfilter}, function(error2, result){
        if (error2) {
            res.send({"error":"true", "status":"500", "message":"Oops! Some error occurred while updating the "+activityname+" on Post"});
        } else {
            res.send({"error":"false", "status":"201", "message":"Successfully Updated "+activityname+" on Post"});
        }
    });

};

实际上,我想从测试集合中获取组ID并更新我的辅助表上的所有这些ID,即Test1我知道这个错误生成由于循环。任何人建议我如何解决这个问题。任何帮助表示赞赏

node.js mongodb
2个回答
2
投票

当您尝试为给定请求发送多个响应时,会看到您看到的错误。

你在res.send()打电话给updater()。并且,你在updater()循环中调用for,这意味着你多次调用它。

因此,您最终会在同一请求中多次调用res.send()。这就是导致你看到错误的原因。您只能按要求拨打res.send()一次。

您可能需要做的是积累所有.update()调用的结果,然后在完成所有操作后发送一个响应。但是,你必须决定你想要的行为。你想发送什么样的回应?像这样的一系列对象?

{"error":"false", "status":"201", "message":"Successfully Updated "+activityname+" on Post"}

或者是其他东西?而且,如果您的某个请求出现错误,您希望响应是什么?

由于这是mongodb,你可能想要使用Promise.all()内置mongodb的promises来知道所有.update()调用何时完成。

这是接近它的一种方法:

Test.aggregate([
    {$match: {'ownerid': req.body.ownerid}},
    {$unwind: '$groupname'},
    {$project: {_id:1, groupname :"$groupname",}}
], function(error, data){
    if(error) {
        console.log(error);
    } else {
        //It will return Two group id.
        let promises = [];
        for(var i=0; i<data.length; i++){

            //These are the variables for my custom function which can update my query on another table
            var primaryfilter = {'userid': req.body.ownerid};
            var secondaryfilter = { "groupowned" : { 'groupid': data[i]._id, 'groupname': data[i].groupname } };
            var activityname = 'Group Owned';
            promises.push(updater(Test1, primaryfilter, secondaryfilter, activityname));
        }
        Promise.all(promises).then(function(results) {
            res.json(results);
        }).catch(err => {
            console.log(err);
            res.sendStatus(500);
        })
    }
});


function updater(CollectionName, primaryfilter, secondaryfilter, activityname){
    return CollectionName.update(primaryfilter, {$push: secondaryfilter}).then(function(result) {
        return {"error":"false", "status":"201", "message":"Successfully Updated "+activityname+" on Post"};
    }).catch(function(err) {
        return {"error":"true", "status":"500", "message":"Oops! Some error occurred while updating the "+activityname+" on Post"};
    });
};

0
投票

当您尝试向给定请求发送多个响应时,会看到您看到的错误。试试这段代码:

const async = require('async'); // async node module : npm install --save async

        Test.aggregate([
            {$match: {'ownerid': req.body.ownerid}},
            {$unwind: '$groupname'},
            {$project: {_id:1, groupname :"$groupname"}}
        ], function(error, data){
            if(error) {
                console.log(error);
            } else {
                //Use async module instead of simple javascript loop
                var primaryfilter = {'userid': req.body.ownerid};
                var activityname = 'Group Owned';
                async.eachSeries(data, function(dataItem, asyncCallback){

                    var secondaryfilter = { "groupowned" : { 'groupid': dataItem._id, 'groupname': dataItem.groupname } };

                    Test1.update(primaryfilter, {$push: secondaryfilter}, function(error, result){
                        if (error) {
                            asyncCallback(error);
                        } else {
                            asyncCallback();
                        }
                    });

                }, function(err){
                    if(err) {
                        return res.send({"error":"true", "status":"500", "message":"Oops! Some error occurred while updating the "+activityname+" on Post"});
                    }
                    return res.send({"error":"false", "status":"201", "message":"Successfully Updated "+activityname+" on Post"});
                });
            }
        });
© www.soinside.com 2019 - 2024. All rights reserved.