Vicheanak
Vicheanak

Reputation: 6684

How to Fetch a set of Specific Keys in Firebase?

enter image description here

Say I'd like to fetch only items that contains keys: "-Ju2-oZ8sJIES8_shkTv", "-Ju2-zGVMuX9tMGfySko", and "-Ju202XUwybotkDPloeo".

var items = new Firebase("https://hello-cambodia.firebaseio.com/items");
items.orderByKey().equalTo("-Ju2-gVQbXNgxMlojo-T").once('value', function(snap1){
    items.orderByKey().equalTo("-Ju2-zGVMuX9tMGfySko").once('value', function(snap2){
        items.orderByKey().equalTo("-Ju202XUwybotkDPloeo").once('value', function(snap3){
            console.log(snap1.val());
            console.log(snap2.val());
            console.log(snap3.val());
        })
    })
});

I don't feel that this is the right way to fetch the items, especially, when I have 1000 keys over to fetch from.

If possible, I really hope for something where I can give a set of array like

var itemKeys = ["-Ju2-gVQbXNgxMlojo-T","-Ju2-zGVMuX9tMGfySko", "-Ju202XUwybotkDPloeo"];
var items = new Firebase("https://hello-cambodia.firebaseio.com/items");
    items.orderByKey().equalTo(itemKeys).once('value', function(snap){
       console.log(snap.val());
  });

Any suggestions would be appreciated.

Thanks

Upvotes: 0

Views: 730

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598847

Doing this:

items.orderByKey().equalTo("-Ju2-gVQbXNgxMlojo-T")

Gives exactly the same result as:

items.child("-Ju2-gVQbXNgxMlojo-T")

But the latter is not only more readable, it will also prevent the need for scanning indexes.

But what you have to answer is why want to select these three items? Is it because they all have the same status? Because they fell into a specific date range? Because the user selected them in a list? As soon as you can identify the reason for selecting these three items, you can look to convert the selection into a query. E.g.

var recentItems = ref.orderByChild("createdTimestamp")
                     .startAt(Date.now() - 24*60*60*1000)
                     .endAt(Date.now());
recentItems.on('child_added'...

This query would give you the items of the past day, if you had a field with the timestamp.

Upvotes: 2

Seema Ullal
Seema Ullal

Reputation: 31

You can use Firebase child. For example,

    var currFirebaseRoom = new Firebase(yourFirebaseURL)
    var userRef = currFirebaseRoom.child('users');

Now you can access this child with

     userRef.on('value', function(userSnapshot) {
          //your code
     }

You generally should not be access things using the Firebase keys. Create a child called data and put all your values there and then you can access them through that child reference.

Upvotes: 1

Related Questions