One thing I'm struggling with a bit with Firebase (or other NOSQL dbs, I'm guessing?) is the fact that the ids aren't part of the body of the "row". So if my collection looks like:
Books
|----ldJEIF
|----Title: "A Tale of Two Cities"
|----Author: "Charles Dickens"
|----Body: "It was the best of times..."
|----2difie
|----Title: "Moby Dick"
|----Author: "Herman Melville"
|----Body: "Call me Ishmael..."
If I retrieve the BooksList
, and then select myBook = books[ldJEIF]
to do something with the data, myBook
has no idea where in the list it came from. If I later want to add it to a UserLibrary
, for example, I have to either de-normalize my data, or do some kind of reverse lookup, or pass ldJEIF
around instead of the book object and constantly lookup the data. Am I missing something? What's the best practice way of dealing with this issue?
Grab the ID when you get the data
For Firebase at least, when you retrieve the records, you also get the ID. So a simple solution is to store the ID then. If you don't have a convenient place for it, you can just stick it into the data:
firebaseRef.on('child_added', function(snapshot) {
var data = snapshot.val();
data.id = snapshot.name(); // add the key as an id
});
Of course, if you do this, you have to remember to take it back out before sending the data back to the server.
Use the snapshot
Again specific to Firebase, you could keep a ref to the snapshot and pass that around instead of just the data. I don't really like this approach personally, but I haven't been able to nail down what tidy internal principle it violates.
It is, however, extremely handy in some cases, since you will have a reference to the data, the id, and the Firebase object at any time; rather handy.
Put the ID into the data
A common practice in NoSQL is to just put the ids into the data--there's nothing wrong with this other than a bit of extra storage space--insignificant in most use cases. Then when you fetch records the ID is already in the data and everything is spiffy.
For Firebase, you can generate the id and put it into the data during creation. The following cleverness came from one of their open sourced examples:
var data = {...};
var id = firebaseRef.push().name(); // generate a unique id based on timestamp
data.id = id; // put id into the data
firebaseRef.child(id).set(data);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With