问题
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