I am using a Firebase Database to store user’s reports. Each user is allowed to submit only 10 different reports.
In the example below we have a user named “Jasna Kulja
There're two approaches to this problem. I think for the first approach you've quite figured it how to do so. Only missing thing is to separate the sequential actions of [a] validating the uniqueness of the report and [b] adding the object to the database. There might be a button press for adding the report. I suggest, on the button press get the data snapshot of the required table. As the uniqueness of the report is restricted a single user, fetch all the reports for a single user. Then simply compare the target report with the fetched reports and proceed accordingly. If unique then add or report a duplicate otherwise. The difference (w.r.t your code) is no event listener would be attached. And I think your code processing inline with Firebase data. Here you'll get the data dump, compare it and then update it.
Another approach is to leverage the rules provided by Firebase. Basically, it's same as the first approach, but all work is done by firebase. Here's the code for inserting only unique usernames to Firebase:
"usernames": {
"$usernameid": {
".read": "auth != null",
".write": "auth != null && (!data.exists() || !newData.exists())"
}
}
In the context of your question, you check the uniqueness of the report based on three values. Add the rules for all three values. This would allow inserting the unique reports for each user. But be sure to add the rules correctly as for the scope of the rule must be for a single user, not for all the reports in the database.