Search for last firebase record and incrementing in new record

2

I need to fetch the last code in an array of objects in firebase. Then increment +1 the last code and then save the list with the objects. For now I've created a generic DAO:

//Dao generico

'use strict';

findMaxCode: function(table, callback){
    var refFirebase = this.getInstanceFirebase(table);
    /* Aqui busca ultimo registro na tabela */
    refFirebase.orderByChild("code").on('child_added', function(snapshot) {
        callback(snapshot);
    });
},
saveOrUpdate: function(table, object){
    var refFirebase = this.getInstanceFirebase(table);
    var isSave = (object.code == 0);

    /* Aqui verificar se é para salvar/atualizar */
    if(isSave){
        this.findMaxCode(table, function(last){
            object.code = last.val().code + 1;
            /* Aqui atualize a lista de array */
            refFirebase.push(object);
        })
    }else
        refFirebase.push(object);
},

What happens after you add the new record to the array. From what I understand, it is running again the logic that queries the last record and then ends up becoming a loop.

Would that be the way?

    
asked by anonymous 08.12.2015 / 18:49

1 answer

0

Switch:

   refFirebase.orderByChild("code").on('child_added', function(snapshot) {
     callback(snapshot);
   });

By:

 refFirebase.orderByChild("code").on('child_added', function(snapshot) {
     refFirebase.off();
     callback(snapshot);
 });

So you stop listening before changing the record.

One thing to look at, is if once () would be better, since it reads the data only once.

    
26.01.2017 / 00:03