Delete firestore document based on rule

71 views Asked by At

I created an app where people can upload some images of some themselves.

Now, In order to deal with cases where people can upload inappropriate images, I created a reporting system. What I'm doing is basically every time someone reports the image, the ID of the reporting person is added to an array in firestore like this:

db
    .collection( "Reports" )
    .document( ImageID )
    .update( "Reports", FieldValue.arrayUnion( UID ) );

Now, I want to set a rule that if for example, the size of the array is 5 (5 different people reports the image) that it will automatically delete that image from the cloud.

Is there any way I can do it instead of every time reading the array and check ist size?

Thank you

2

There are 2 answers

0
Frank van Puffelen On BEST ANSWER

The most common way to do that would be through Cloud Functions, which are server-side code that is automatically triggered when (for this use-case) something is written to Firestore. See the documentation on Cloud Functions and the page on Firestore triggers.


An alternate (but more involved) would be to secure access through a query and security rules. In this scenario you'd:

  1. Add a reportCount to the document, and ensure this gets updated in sync with the reports.
  2. From the application code use a query to only request images with a reportCount less than 5.
  3. Use security rules to only allow queries with that clause in it.

As said, this is more involved in the amount of code you write, but the advantage is that no server-side code is involved, and that documents are immediately blocked when too many reports come in for them.

0
Francesco Colamonici On

You can create a trigger on your Reports collection.

export const updateReportTrigger = functions.firestore
  .document('Reports/{ImageID}')
  .onUpdate(onUpdate)

async function onUpdate({ before, after }, context) {
  const newData = after.data()
  if (newData && newData.Reports && newData.Reports.length > 5) {
    // put your delete logic here
    // you can access the document id through context.params.ImageID
  }
}