0

I am using Firebase with Nodejs. I want to limit number of records inbattleReports by number N. But not just limit. If new data will come and there is already N records in battleReports, delete oldest one and add new one. I want to implement something like circular queue or buffer. Is it possible?

  players: {
    'player1-id': {
      battleReports: {
        'battle-report-1': {/* report object */},
        'battle-report-2': {/* report object */},
        'battle-report-3': {/* report object */}
        // ... 
      }
    },
    'player2-id': {
      battleReports: {
        'battle-report-1': {/* report object */},
        'battle-report-2': {/* report object */},
        'battle-report-3': {/* report object */}
        // ... 
      }
    },
    // ...
  }
ReyAnthonyRenacia
  • 17,219
  • 5
  • 37
  • 56
tprieboj
  • 1,680
  • 6
  • 31
  • 54

1 Answers1

1

Sure, but I would suggest changing the children of battleReports to use auto-generated key (e.g. the push method).

That way the battleReports will always be sorted in order by when they were added.

Regardless, create the database function that looks something like this:

this.battleReportLimiter = functions.database.ref('battleReports/{newReport}').onCreate(event => {
  return admin.database().ref('battleReports').orderByKey().limitToFirst(1).once('value').then(event => {
    return admin.database().ref('battleReports').child(event).remove();
  });
});

You don't have to use auto-generated keys and orderByKey(), you can also use the other rules here if you want (that requires an indexOn: [<child>] rule in your database rules).

Summary: the solution is just to create some sort of ordering technique either by key or by child/value. Then you just need to listen for onCreate using a variable like {newReport} or listen for childAdded on battleReports. Then use any technique to get the oldest (always the first key when auto-generated) and then delete it.

tprieboj
  • 1,680
  • 6
  • 31
  • 54
Drei
  • 669
  • 1
  • 6
  • 22