How to request related entries in Firebase?

Given this database structure in Firebase:

{ "users": { "user1": { "items": { "id1": true } }, "user2": { "items": { "id2": true } } }, "items": { "id1": { "name": "foo1", "user": "user1" }, "id2": { "name": "foo2", "user": "user2" } } } 

which is a more efficient way to query elements belonging to a specific user?

Firebase docs seem to offer this:

 var itemsRef = new Firebase("https://firebaseio.com/items"); var usersItemsRef = new Firebase("https://firebaseio/users/" + user.uid + "/items"); usersItemsRef.on("child_added", function(data){ itemsRef.child(data.key()).once("value", function(itemData){ //got the item }); }); 

but the .equalTo () request also works:

 var ref = new Firebase("https://firebaseio.com/items"); ref.orderByChild("user").equalTo(user.uid).on("child_added", function(data){ //got the item }); 

The latter code looks more concise and does not require the denormalization of element keys in user records, but it is unclear if this is a less efficient methodology (assuming that I am creating an index for the "user").

thanks.

+6
source share
1 answer

This is pretty old, but when working on a firebase-enabled application, I often encountered similar problems.

.equalTo is more time-efficient (especially if one user owns a large number of elements). Although n + 1 subscriptions do not result in n + 1 network backlinks to the cloud, there is some measure of performance with so many open subscribers.

In addition, the .equalTo approach does not denormalize your data.

However, there is a question: when you want to protect data, the .equalTo approach may stop working at all.

To allow the user to call orderByChild ("user"). equalTo (user.uid), they must have read privilege for the "items" collection. This read permission is valid for the entire subdocument rooted in / items.

Summary If user1 fails to find out about user2 elements, you should use the BYOI approach (create your own index). This way you can verify that the user only reads the elements that are placed in their index.

Finally, a disclaimer :) I use firebase only for a short period of time, all I have is a few tests and documentation. If I am wrong, please correct me.

+1
source

Source: https://habr.com/ru/post/978734/


All Articles