Yugue Chen
Yugue Chen

Reputation: 79

Firestore Security Rule List Check Duplicate

Let's say that request.resource.data[field] is a list. I am trying to check if any of the items in the list is a duplicate of the other items. In other words, I am checking if any of the items are repeated more than once inside the list. I read the documentation and reference related to list, and did not find a way to implement this. Is this possible to do?

Upvotes: 0

Views: 102

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317402

You can check to see if there are any duplicates in a List type field by:

  1. Converting the List into a Set using toSet() (which cannot contain duplicates
  2. Comparing the size of the List to the size of the Set

If the size of the set is less then the size of the list, then you know that there was at least one duplicate that got removed. So, something like this will return true if there was a duplicate in the list:

listField.toSet().size() < listField.size()

Upvotes: 2

Related Questions