1

In my Firebase I have a number of items of data, in this case they are announcements. Each announcement has a child property of "ID", which is unique for every announcement. Is there a way I can enforce that the ID is unique when I post announcements to the database via rest? That is, if I tried to add an announcement with the same ID twice, the second one would fail. I suspect I can do something with rules, but I am not sure.

Thanks, Declan

declanjscott
  • 351
  • 1
  • 2
  • 10

1 Answers1

4

The best way to achieve this would be to identify each announcement by the ID itself instead of having it be a child property. Then you can use a security rule like:

".write": "!data.exists()"

If someone tries to write an announcement with an ID that already exists the write rule will evaluate to false and therefore it will be disallowed.

You can use the push() method to generate unique identifiers that are chronologically ordered.

Anant
  • 7,408
  • 1
  • 30
  • 30
  • No, you can have multiple children under the key "gonzagan" - if you try writing a child with key "01" using set() it will fail because "01" already exists, but setting something with "02" will work. – Anant May 03 '13 at 16:56
  • Do you (@Anant) mind putting up a gist of a simple example of it working? E.g. assume I am logged in, I want to create a group, I can only do so if the group name is not already in existence. Ignore the login, all of that, just the code (and rules) around creating the group and catching uniqueness? – deitch Jul 18 '13 at 13:44