Search last firebase record and incrementing in new record

Asked

Viewed 598 times

2

I need to fetch the last code in an array of objects in the firebase. Then increment +1 on that last code and then save the list with the objects. For now I 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 including the new record in the array. From what I understand, it is running again the logic that queries the last record and then ends up turning a loop.

That would be the way?

1 answer

0

Change:

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

For:

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

So you stop listening before you change the record.

One thing to look at is whether Once() would be better, since it reads the die only once.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.