Rule entries duplicates firebase not working

本秂侑毒 提交于 2021-02-10 16:59:32

问题


I have an application in android that registers sellers, which have a unique email, I am storing them in firebase. Create a rule to not allow duplicates to be added but it does not seem to work. What am I doing wrong?

{
 "rules": {
   ".read": true,
   ".write": true,
   "sellers": {
     "$seller": {
       "email": {
         ".write": "!data.exists()"
       }
     }
   }
 }
}

my method to add

 public void addSeller(Seller seller){
    HashMap<String,Seller> map= new HashMap<>() ;
    String email = seller.getEmail().replace(".",",");
    map.put(email,seler);
    database.child("sellers").setValue(map);
}

回答1:


You're calling push(), which generates a new child that is statistically guaranteed to be unique.

If you want to ensure unique email addresses, you will have to keep a collection where the (encoded) email addresses are the keys:

emails
  pete@somedomain,com
  puf@somedomain,com

With this structure, the following rule will work to ensure an email address can only be written once:

{
 "rules": {
   ".read": true,
   "emails": {
     "$email": {
       ".write": "!data.exists()"
     }
   }
 }
}

The topic of unique values comes up regularly, so I recommend you also check out these:

  • Firebase android : make username unique
  • How do you prevent duplicate user properties in Firebase?
  • Enforcing unique usernames with Firebase simplelogin
  • unique property in Firebase
  • Firebase Unique Value
  • What Firebase rule will prevent duplicates in a collection based on other fields?


来源:https://stackoverflow.com/questions/44203936/rule-entries-duplicates-firebase-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!