0

I have data structure like this:

Employees (Collection) > {EmployeeID} (Documents) > Chat (Collection) > {ChatId} (Documents).

In chat collection each document having 3 fields. 1. senderName, 2. sendTimestamp, 3. messageText.

I want to delete chats which are older than 7 days (from today).

I think it might be possible through cloud function but I am really basic user and don't know much about cloud functions. Please note that I don't want to make it automatically (cron job). I will do it manually on daily basis or whenever I wish.

I really searched a lot for this but its really hard. Please help me.

Pooja
  • 475
  • 5
  • 14

1 Answers1

0

A big part of this task involves querying a sub collection. You can read more about this idea here: Firestore query subcollections

There are basically two options at the time of writing this:

  1. Query the entire top level collection (Employees) something like db.collection('Employees').get(). Then you would have to loop through each employ object querying for their sub collection (Chat) based on their date range. Firestore query by date range for more reading on querying by a date in firestore. This could result in a large amount of reads depending on the number of Employee documents, but is the "easiest" approach in terms of not having to make changes to your data models/application.
  2. Restructure your data to make the sub collection Chat a top level collection. Then you can do a query on this top level collection by the date. Less reads, but may not be as feasible depending on if this app is in production/willingness to make code changes.

A Function would definitely be able to accomplish this task either way you decide to approach it. One thing to note is that a Function executes using the Admin SDK, meaning it can basically ignore security rules set up on your Firestore.

CuriousGeorge
  • 519
  • 3
  • 12
  • Thanks for answer. I think 1st option is helpful but amount of reads is really serious problem because I already have more than 5k records. Due to this existing data, your 2nd option is not useful. Thanks for answer. – Pooja Apr 10 '19 at 09:08