Search code examples
saveibm-mobilefirstsavechangesjsonstoremultivalue

How save multiple values JSONStore


I need to replace multiple value in JSONStore of IBM Worklight. In this way is saved only first value. Why?

 .then(function() {                             
   for (var index = 0; index < elencoSpese.length; index++) {                                          
       var spesa = elencoSpese[index];                              
       var spesaReplace = {_id: spesa.id, json: spesa};                                 
       spesa.id_nota_spesa = idNotaSpesa;                               
       spesa.checked = true;                            
       WL.JSONStore.get(COLLECTION_NAME_SPESE).replace(spesaReplace);
    }
  })

Solution

  • You want to build an array of JSONStore documents and pass it to the replaceAPI. For example:

    .then(function() {
    
        var replacementsArray = [];
    
        for (var index = 0; index < elencoSpese.length; index++) {
            var spesa = elencoSpese[index];
            var spesaReplace = {_id: spesa.id, json: spesa};
            spesa.id_nota_spesa = idNotaSpesa;
            spesa.checked = true;
            replacementsArray.push(spesaReplace);
        }
    
        return WL.JSONStore.get(COLLECTION_NAME_SPESE).replace(replacementsArray);
    
    })
    .then(function (numOfDocsReplaced) {
        // numOfDocsReplaced should equal elencoSpese.length
    })
    

    I assume this happens in the JavaScript implementation of the JSONStore API, if that's the case the answer is in the documentation here. The JavaScript implementation of JSONStore expects code to be called serially. Wait for an operation to finish before you call the next one. When you call the replace multiple times without waiting, you're calling the API in parallel instead of serially. This should not be an issue in the production environments (i.e. Android, iOS, WP8 and W8).