0

I have an array, and for each row I need to do findIfExist and save into mongodb. The code is here:

router.post('/namespaceUpload', function(req, res,next) {
   var data=req.body;
   var totalRows=data.allRows.length;

   var conceptObject ={};
   var existingConcept;

   for (var i=0;i<totalRows;i++){
        async.series([
            conceptPrepare,
            conceptFind,
            conceptSave,
            ], function (err, result) {
                    console.log('kraj');
                    res.json('Ok'); 
        });
    }

    function conceptPrepare(callback){
        conceptObject.name= data.allRows[i].name;
        conceptObject.user= data.userId;
        callback();
    }
    function conceptFind(callback){
        namespaces.find({name: conceptObject.name}, function(err, result) { 
        if (err)
            next(err);
        else {
            if (result.length==0){
                console.log('0');
                existingConcept='';
            } else {
                console.log(result.length);
                existingConcept=result[0];
            }
        }
        callback();
        });
    }


    function conceptSave(callback){
        var namespace = new namespaces();
        if (existingConcept==''){
            namespace.name=conceptObject.name;
            namespace.description=conceptObject.description;
            namespace.lastUpdate.user=conceptObject.user;
            namespace.save(function(err) {
            if (err)
             return next(err);
             callback();             
            })

        }

    }

So I Used async.series, but only last record is written in database as much times as many array members i have. Also, I get an error " Can't set headers after they are sent." Any idea?

  • Possible duplicate of [Node.js Error: Can't set headers after they are sent](http://stackoverflow.com/questions/7042340/node-js-error-cant-set-headers-after-they-are-sent) – alexmac Apr 18 '16 at 22:54
  • @AlexanderMac I think the bigger issue here is the "loop control" and not realizing the concept that you send the response when the loop is complete. Actually only just [answered a similar issue](http://stackoverflow.com/a/36705570/2313887) within the last hour. That shows how to handle the flow and respond only when the loop is complete. – Neil Lunn Apr 18 '16 at 23:58
  • @NeilLunn yes, it seems that you're right. – alexmac Apr 19 '16 at 00:12

1 Answers1

0

You're getting the Can't set headers after they are sent error message because you 're not allowed to return smtg eg : res.send,res.render more than one time but in your for loop, it goes totalRows times try to return one value at the end of the loop

Akram Saouri
  • 1,179
  • 8
  • 15