dontknowhy
dontknowhy

Reputation: 2866

remove old data in Firebase

I know this question a lot here, But I don`t know about this. This is about chat app.

When message get stored into the firebase database. It would become bigger and bigger as time goes by, I want to delete it. and when should I delete this? I just want to left just only last 10 data. It means if I out the app and again go in, It appears only last 10 sentence and I know about the function limitToFirst and limitToLast (but this is not the delete thing.)

If I pay firebase server, you know, if database's data is large It will be more expensive. but I just want to leave just last 10 sentences at least. when they did come back then they can see the last 10sentence and want to delete except for this. how do I do this?

I saw the answer using the date, but I don`t want that. Is that only answer? If I must do that when I get to delete them? When do I invoke the delete function?

I know how to do that almost, but when? If in the app, there are so many friends and I open the chat screen to chat my friend. That time should I delete them using remove function? How am I saving this for server payment?

I don`t want cost a lot. and I want them to be clear, not dirty in my Firebase database console. so want to delete them. Which is the I have to do? Which time is the best time that I should delete them? When open it ? or when close it ? or when users stop the my app.

Upvotes: 1

Views: 2658

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138824

You can achieve this in a very simple way. You can use the getChildrenCount() method on the node in which you hold the messages to see the exact number of messages. If you are using as an identifier the random key generated by the push() method, it's very easy to delete the extra messages. Because the records are by default order by date, you can easily query your database using limitToLast(limit) method and than delete the messages like this:

yourRef.child("messages").child(messageId).removeValue();

Another way to achieve this is to use Cloud Functions for Firebase.

Hope it helps.

Upvotes: 1

Oussema Aroua
Oussema Aroua

Reputation: 5329

you can use firebase functions to delete old data when new ones added to the database that is the best time, you can keep the last 100 messages or less.

Upvotes: 0

Related Questions