Custom IDs In Firebase
Firebase is a service that allows us to create real-time apps without having a native back-end(server). Storing and retrieving of data in real-time is done directly from the browser(front-end), i.e. no back-end services is required to fetch the data.
Whenever we save data in Firebase, it generates a unique identification ID for each object. Sometimes it’s hard to maintain or traverse the data on the basis of these randomly generated IDs, because the only way to access data in Firebase is via URL reference (refObject/books//title) for the particular node. So sometimes we need to store data object with our own custom keys.
[code language=”javascript”]var onComplete = function(error) {
if (error) {
console.log(‘Operation failed’);
} else {
console.log(‘ Operation completed’);
}
};[/code]
We can save data into firebase using push() method.
[code language=”javascript”]var booksRef = ref.child("books");
booksRef.push({
author: " Adam Freeman",
title: "Pro AngularJS"
}, onComplete);
booksRef.push({
author: "Niall OHiggins",
title: "MongoDB and Python"
}, onComplete);[/code]
The above code saves two objects into my data store and if the operation is successful, an auto-generated ID by Firebase is set as key for respective data objects.
Now, the data store in Firebase will look like:
[code language=”javascript”]{
"books" : {
"-Jldh2kvv9KyrkBuTTjV" : {
"author" : " Adam Freeman",
"title" : "Pro AngularJS"
},
"-Jldh2kx0AgFXU1-Umnx" : {
"author" : "Niall OHiggins",
"title" : "MongoDB and Python"
}
}
}[/code]
Sometimes, we need to store data with custom IDs. Such as Email-ID, UserName etc.
We can use set() method to save our data in Firebase.
[code language=”javascript”] var booksRef = ref.child("books");
booksRef.child(‘Adam Freeman’).set({
title: "Pro AngularJS"
}, onComplete);
booksRef.child(‘Niall OHiggins’).set({
title: "MongoDB and Python"
}, onComplete);[/code]
Now, the data store in Firebase will look like :
[code language=”javascript”]{
"books" : {
"Adam Freeman" : {
"title" : "Pro AngularJS"
},
"Niall OHiggins" : {
"title" : "MongoDB and Python"
}
}
}[/code]
U cant do this better try other solution maybe string containing combination of unique id
There is one problem with e-mail as custom ID. When I try it I get error “Firebase.child failed: First argument was an invalid path: “john.doe@example.com”. Paths must be non-empty strings and can’t contain “.”, “#”, “$”, “[“, or “]””