Search code examples
angulartypescriptfirebasefirebase-realtime-databaseangularfire

Batch create/remove with Firebase Real time db


I use Firebase real time db like so:

 createSoldLead(soldLead: SoldLeadModel): void {
    const soldLeadsReference = this.angularFireDatabase.list<SoldLeadModel>(
      `groups/${this.groupId}/soldLeads`
    );

    const leadsReference = this.angularFireDatabase
        .list<SoldLeadModel>(
      `groups/${this.groupId}/leads`
    );

    soldLeadsReference.set(soldLead.id.toString(),soldLead);

    leadsReference.remove(soldLead.id.toString());
  }

This is working fine. But how can I do this as a batch create/remove? i.e. make sure they both succeed

I saw this blog. But no idea how to apply it on my use case?


Solution

  • You can use a single multi-path update to write multiple nodes at different paths.

    The equivalent of your two calls will be something like this:

    let updates = {};
    updates[`groups/${this.groupId}/soldLeads/${soldLead.id}`] = soldLead;
    updates[`groups/${this.groupId}/leads/${soldLead.id}`] = null;
    
    firebase.database().ref().update(updates);
    

    Setting a node value to null removes that node.