0

I have database structured like this:

enter image description here

I am using secret key in my security rules. I could not find any childByAutoId function in nodejs firebase package, so I am using timestamp for each new node. I would like to keep every node something about one month in database. For example on every first day in month nodejs would delete nodes from two months back. What is the simple/best way to do it? Do I need to change database structure in order to archive it? Or is is possible for firebase to do it for me? This is how I write into database:

import { initializeApp } from 'firebase/app';
import { getDatabase, ref, set, remove } from 'firebase/database'
const firebaseApp = initializeApp(config);
const db = getDatabase(firebaseApp);

function writeUserData(secret, userName, timestamp) {
    return set(ref(db, `${secret}/${timestamp}`), {
        name: userName
    });
}
andz
  • 274
  • 1
  • 3
  • 12
  • It might be best to use a Cloud function that runs on 1st of every month (`0 0 1 * *`) and then follow this answer; [Delete firebase data older than 2 hours](https://stackoverflow.com/q/32004582/13130697) – Dharmaraj Mar 18 '22 at 12:08

1 Answers1

1

The equivalent of childByAutoId in most other Firebase SDKs is called push. The key generated by push will be the same format as by childByAutoId.


If you know the secret key, you can find all outdated keys under there with the approach I showed here: Delete firebase data older than 2 hours

The biggest difference is that you have the timestamp in the key, so your query should be something like:

const ref = db.child('Xhj0yJux....Dm8R');
var oldItemsQuery = ref.orderByKey().endAt(cutoff);

As Dharmaraj commented, you'll typically want to run this code in Cloud Functions, Cloud Run, or another trusted environment where you can schedule it to run periodically.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807