A way to enforce a unique property in Firebase

2020-02-15 06:22发布

问题:

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

回答1:

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.