I have database structured like this:
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
});
}
CodePudding user response:
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.