Reputation: 2499
While modeling with Firebase readtime DB, stuck with deciding unique key.
My users collection is identified as email ID.
So my aim is modeling DB such as below.
{
"users": {
"[email protected]": {
"name": "aa",
"addr": "new york",
"tel": "3224323"
},
"[email protected]": {
"name": "bb",
"addr": "new york",
"tel": "3224323"
},
"[email protected]": {
"name": "bb",
"addr": "new york",
"tel": "3224323"
},
"[email protected]": {
"name": "cc",
"addr": "new york",
"tel": "3224323"
}
}
}
But Firebase doesn't allow some special character as it's key. such as @
, :
, etc.
How can I fix my modeling to adapt for Firebase?
Upvotes: 2
Views: 2248
Reputation: 474
Actually firebase don't allow only ".", "#", "$", "[", or "]" characters...:
Uncaught (in promise) Error: Reference.child failed:
First argument was an invalid path = "firebase/[email protected]/data".
Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"
... so the problem in this situation is only '.' character.
So if in your usecase it would be ok to change '.' with something else you might do this rules:
{
"rules": {
"users": {
"$email": {
".read": true,
".write": "$email === auth.token.email.replace('.', ',')",
}
}
}
}
(Inspired by: https://firebase.google.com/docs/reference/security/database#replacesubstring_replacement)
and from now on just save data like this:
const email = firebase.auth().currentUser.email.replace(/\./g, ',');
// test@gmail,com
await firebase.database()
.ref(`users/${email}/data`)
.set({
name: "eee",
addr: '56 Barker Close',
tel: '1234567890'
});
so at the end data will look:
{
"users": {
"aa@dd,com": {
"name": "aa",
"addr": "new york",
"tel": "3224323"
},
"bb@dd,com": {
"name": "bb",
"addr": "new york",
"tel": "3224323"
},
"cc@dd,com": {
"name": "bb",
"addr": "new york",
"tel": "3224323"
},
"dd@dd,com": {
"name": "cc",
"addr": "new york",
"tel": "3224323"
},
"test@gmail,com": {
"name": "eee",
"addr": "56 Barker Close",
"tel": "1234567890"
}
}
}
Upvotes: 2
Reputation: 80924
You can change from having an email as a unique key to having the unique id that you get from firebase authentication.
If you use the UID
, then you will be able to connect the firebase database with each other in the authentication, since it is provided by the firebase authentication. Also, it is much better since if a user changes his email then you need to change your database to adapt to the user's change.
Check the following:
https://firebase.google.com/docs/auth/web/manage-users#get_a_users_profile
Upvotes: 2