How to have Firebase automatically delete values older than 30 minutes
You can use Cloud Functions for Firebase and set up a cron job that runs, say, every five minutes and checks for timestamps older than 30 minutes.
As Will commented, that blog post is useful to learn about scheduling Cloud Functions. Here are some other useful resources to get you started:
Getting Started with Cloud Functions for Firebase - YouTube
Cloud Functions for Firebase Documentation
Cloud Functions Samples
Timing Cloud Functions for Firebase using an HTTP Trigger and Cron - YouTube
How to create an auto delete mechanism for firestore? (deleting data after time period)
Since late 2022 Firestore supports configuring a time-to-live policy on collections. See the documentation on managing data retention with TTL policies for full details.
I left my previous answer below, just in case somebody wants to roll their own solution.
The below is outdated, and just left for reference. For the latest, see /p>
There is no built-in time-to-live mechanism in Cloud Firestore. The common approach is to run a piece of code at an interval, e.g. a Cloud Function triggered by something like cron-job.org.
Have a look at these questions for samples:
- Delete firebase data older than 2 hours
- How to delete firebase data after "n" days
- Impelementing aging in a Firebase real time database
- How to schedule a Cloud Functions to run in the future in order to build a Firestore document TTL
While these are for the Firebase Realtime Database, the same approach applies to Cloud Firestore.
How to delete firebase data after n days
Say that you have a data structure with nodes line this:
-KItqNxLqzQoLnUCb9sJaddclose
time: "Thu Apr 28 17:12:05 PDT 2016"
timestamp: 1461888725444
Each such node has a timestamp
property that indicates when it was created. Preferably you'd set this property using Server Timestamp.
With this data structure, you can easily build a query that returns only the items older than 30 days and removes them:
long cutoff = new Date().getTime() - TimeUnit.MILLISECONDS.convert(30, TimeUnit.DAYS);
Query oldItems = ttlRef.orderByChild("timestamp").endAt(cutoff);
oldItems.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot itemSnapshot: snapshot.getChildren()) {
itemSnapshot.getRef().removeValue();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
How to auto delete messages on firebase
It looks like you're trying to deploy code that require Node 8 (since it uses =>
notation) to an environment that doesn't support it.
On solution is to upgrade the environment to support Node 8. The alternative is to modify the code to not require Node 8 anymore, which can be done with:
exports.deleteOldItems = functions.database.ref('/mensagens/{idone}/{idtwo}/{pushid}').onWrite(function(change) {
var ref = change.after.ref.parent; // reference to the parent
var now = Date.now();
var cutoff = now - CUT_OFF_TIME;
var oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff);
return oldItemsQuery.once('value').then(function(snapshot) {
// create a map with all children that need to be removed
var updates = {};
snapshot.forEach(function(child) {
updates[child.key] = null;
});
// execute all updates in one go and return the result to end the function
return ref.update(updates);
});
});
This type of rewrite is fairly common in modern JavaScript, so I assume you're new to this. If you are new to JavaScript, Cloud Functions for Firebase is not the best way to learn it. I recommend first reading the Firebase documentation for Web developers and/or taking the Firebase codelab for Web developer. They cover many basic JavaScript, Web and Firebase interactions. You could also use the Admin SDK in a local Node.js process, which can be debugged with a local debugger. After those you'll be much better equipped to write code for Cloud Functions too.
Deleting Firebase data after a certain time
The orderByChild()
sorting method is very forgiving. The children being sorted are not required to have a member with the specified field name. The documentation explains that those children are assigned a null value and appear first in the sort. Thus, if the reference used to create a query is incorrectly located, the query doesn't fail and instead will typically return all the children of that location.
You created your oldBug
query using mDatabase
where:
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
This is one level too high. It should be:
Query oldBug = mDatabase.child("Users").orderByChild("timeStamp").endAt(cutoff);
Related Topics
Collectionview Duplicate Cell When Loading More Data
Ignoring the Dynamic Type in iOS: Accessibility
Swift 3- How to Get Button in Uicollectionviewcell Work
Uisegmentedcontrol iOS 13 Clear Color
Initializing Swift Properties That Require "Self" as an Argument
Avplayerviewcontroller Using Audio-Only Avplayer
How to Hide "Back to Safari" from Status Bar in iOS9
Uilabel, Uifont and Utf-8 Triangle
Uploading Image with iOS App to Server File Size Is Too Large
How to Sign Out of Apple After Being Authenticated
Executefetchrequest Throw Fatal Error: Nsarray Element Failed to Match the Swift Array Element Type
Open Uiimagepickercontroller in Landscape Mode
How to Upload Multiple Image on Firebase Using Swift
Programmatically Added Constraint Not Working
iOS 8.3 and Later, Facebook Share Text Not Inserted
Nspredicate to Match "Any Entry in an Nsdatabase with Value That Contains a String"