Start a new topic
Answered

Problem with for loop in Business Logic

Hey guys,


I am having troubles with collectionAccess.find/findAsync and for loops.

I am passing a JSON object like this one:


{"parkinglot":"a","countryId":"Argentina","parkingtype":"Public","jsongw":[{"gatewayid":"1","parkinglot":"a","levelgw":"1","ip_addr":"1","positiongw":"1"},{"gatewayid":"2","parkinglot":"a","levelgw":"2","ip_addr":"2","positiongw":"2"},{"gatewayid":"3","parkinglot":"a","levelgw":"3","ip_addr":"3","positiongw":"3"}],"jsonnode":[{"productid":"4","parkinglot":"a","levelnode":"4","spot":"4","positionnode":"4"},{"productid":"5","parkinglot":"a","levelnode":"5","spot":"5","positionnode":"5"},{"productid":"6","parkinglot":"a","levelnode":"6","spot":"6","positionnode":"6"}]}


First I use findAsync to look in a Collection if the key "parkinglot" is there, and if it's there I do an update, if it isn't there I insert a new document. This works fine.


Then, I check the length of the "jsongw" key (in this case is 3) and I want to find/findAsync for each one of the jsongw objects and do the same that I did with the "parking lot":  if it's there I do an update, if it isn't there I insert a new document.


I thought of using a for loop [for(i=0;i<jsongw.length;i++)] and inside the for do the collecionAccess.find/findAsync but the problem is that I can't figure out how to pass the correct index of the object to do the find and then the update or inter.


Here's the code:


var findData = modules.collectionAccess.collection(collection).findAsync({"Name":body.parkinglot});

  findData.then(function (docs) {

    if(JSON.stringify(docs) != JSON.stringify([])){

      updateDocument(collection,docs,body);

    }

    else{

      insertDocument(collection,body);

    }

  }, 

  function(err){

    logger.error('Query failed: '+ err);

  }).then(function(){

    if(body.jsongw != '[]'){

      //Here is where I have the problem

      for(var i=0;i<body.jsongw.length;i++){

        modules.logger.info('iii'+i);

        jsongwaux={'gatewayid':body.jsongw[i].gatewayid,'parking_id':body.jsongw[i].parking_id,'levelgw':body.jsongw[i].levelgw,'ip_addr':body.jsongw[i].ip_addr,'positiongw':body.jsongw[i].positiongw};

        var findData2 = modules.collectionAccess.collection('Gateway').findAsync({"gateway_id":jsongwaux.gatewayid});

        findData2.then(function (docsgw) {

          if(JSON.stringify(docsgw) != JSON.stringify([])){

            modules.logger.info('jsongw old');

            updateDocumentGW('Gateway',docsgw,jsongwaux,i);

          }

          else{

            modules.logger.info('jsongw new');

            modules.logger.info('ii'+i);

            insertDocumentGW('Gateway',jsongwaux,i);

          }

        }, 

        function(err){

          logger.error('Query failed: '+ err);

        });

      }

    }

  }).then(function(){

    if(body.jsonnode != '[]'){

     //Here is where I have the problem

      for(var j=0;j<body.jsonnode.length;j++){

        modules.logger.info('jjj'+j);

        jsonnodeaux={'productid':body.jsonnode[j].productid,'parking_id':body.jsonnode[j].parking_id,'levelnode':body.jsonnode[j].levelnode,'spot':body.jsonnode[j].spot,'positionnode':body.jsonnode[j].positionnode};

        var findData3 = modules.collectionAccess.collection('Nodo').findAsync({"product_id":jsonnodeaux.productid});

        findData3.then(function (docsnode) {

          if(JSON.stringify(docsnode) != JSON.stringify([])){

            modules.logger.info('json node old');

            updateDocumentNode('Nodo',docsnode,jsonnodeaux,j);

           

          }

          else{

            modules.logger.info('json node new');

            modules.logger.info('jj'+j);

            insertDocumentNode('Nodo',jsonnodeaux,j);

          

          }

        }, 

        function(err){

          logger.error('Query failed: '+ err);

        });

      }

    }

    response.complete(200);

  });


}


/****************************************************************************************************/

//Funciones


var insertDocument = function(collection,body,callback) {

  modules.collectionAccess.collection(collection).insert({"Name":body.parkinglot,"Country":body.countryId,"Region":body.stateId,"City":body.cityId,"Type":body.parkingtype,"Levels":body.levels}, 

  function(err, result) {

    if(!err){

      modules.logger.info('documento insertado parking');

      callback();

    }

  });

};


var updateDocument = function(collection,docs,body,callback) {

  

  modules.logger.info(docs[0]._id);

  modules.collectionAccess.collection(collection).update({"_id":docs[0]._id},{$set:{"Country":body.countryId,"Region":body.stateId,"City":body.cityId,"Type":body.parkingtype,"Levels":body.levels}},

  function(err, result) {

    if(!err){

      modules.logger.info('documento actualizado parking');

      callback();

    }

  });

};


var insertDocumentGW = function(collection,body,i,callback) {

  modules.logger.info('insert gw');

  modules.logger.info('i'+i);

  modules.collectionAccess.collection(collection).insert({"gateway_id":body.gatewayid,"parking_id":body.parking_id,"level_id":body.levelgw,"IP_address":body.ip_addr,"Position":body.positiongw}, 

  function(err, result) {

    if(!err){

      modules.logger.info('documento insertado gw');

      callback();

    }

  });

};


var updateDocumentGW = function(collection,docs,body,i,callback) {

  modules.logger.info('update gw');

  modules.collectionAccess.collection(collection).update({"_id":docs[0]._id},{$set:{"parking_id":body.parking_id,"level_id":body.levelgw,"IP_address":body.ip_addr,"Position":body.positiongw}},

  function(err, result) {

    if(!err){

      modules.logger.info('documento actualizado gw');

      callback();

    }

  });

};

var insertDocumentNode = function(collection,jsonnodeaux,j,callback) {

  modules.logger.info('insert node');

  modules.logger.info('j'+j);

  modules.collectionAccess.collection(collection).insert({"product_id":jsonnodeaux.productid,"parking_id":jsonnodeaux.parking_id,"level_id":jsonnodeaux.levelnode,"Parking_Spot_Number":jsonnodeaux.spot,"Position":jsonnodeaux.positionnode}, 

  function(err, result) {

    if(!err){

      modules.logger.info('documento insertado nodo');

      callback();

    }

  });

};


var updateDocumentNode = function(collection,docs,jsonnodeaux,j,callback) {

  modules.logger.info('update node');

  modules.collectionAccess.collection(collection).update({"_id":docs[0]._id},{$set:{"parking_id":jsonnodeaux.parking_id,"level_id":jsonnodeaux.levelnode,"Parking_Spot_Number":jsonnodeaux.spot,"Position":jsonnodeaux.positionnode}},

  function(err, result) {

    if(!err){

      modules.logger.info('documento actualizado nodo');

      callback();

    }

  });

};


Cna anyone help me?


Thanks!


Best Answer

Hi Carlos,


If I understand correctly in the first step you update/insert one parkinglot object and in the next step, you update/insert multiple gateway objects.


You seem to be having this issue because in the for loop, you are firing multiple async requests but the for loop doesn't wait for them tom complete.


You should take a look at async library available in BL: http://devcenter.kinvey.com/rest/reference/business-logic/reference.html#async-module


Using async, you can ensure that your code executes in proper intended order.


Let me know once you have taken a look at it.



Regards,

Wani


Answer

Hi Carlos,


If I understand correctly in the first step you update/insert one parkinglot object and in the next step, you update/insert multiple gateway objects.


You seem to be having this issue because in the for loop, you are firing multiple async requests but the for loop doesn't wait for them tom complete.


You should take a look at async library available in BL: http://devcenter.kinvey.com/rest/reference/business-logic/reference.html#async-module


Using async, you can ensure that your code executes in proper intended order.


Let me know once you have taken a look at it.



Regards,

Wani


1 person likes this

Hi Wani,


Thank you so much for your answer. I used the forEachOf method of the Async module and it worked just perfect!


Regards,

Carlos

Login or Signup to post a comment