1

I am using Firebase Database for my Android application and cloud functions. As Firebase stores data in JSON format. Each user has some unique id which assigns to user.

I want to know if there is any way to get multiple users data on a single request. If you see below code it will fetch data only of passed user id.

db
    .ref("/users/" + request.query.userId)
    .once("value")
    .then(function(snapshot) {

I have 10 user ids of which I want to get data on a single request in nodejs. What is the way to get this ?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
N Sharma
  • 33,489
  • 95
  • 256
  • 444

2 Answers2

3

Store them in an array like this:

var promArr = []
var snapshotData = []
promArr.push(
db
    .ref("/users/" + request.query.userId) //put here unique usernames
    .once("value")
    .then(function(snapshot) {
    snapshotData.push(snapshot.val())
    })
return Promise.all(promArr).then(snap =>  {
//loop through snapshotData here
})
J. Doe
  • 12,159
  • 9
  • 60
  • 114
  • 1
    @Williams: this is indeed the common approach and is not as slow as you may think, since Firebase pipelines the requests over a single connection. For an explanation of that, see my answer here http://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786 – Frank van Puffelen Aug 05 '17 at 14:45
  • @FrankvanPuffelen Thanks, your posts are really helpful :) – N Sharma Aug 06 '17 at 18:31
3

This can be written much cleaner:

const records = [
  admin.database().ref(`users/${userId1}`).once('value'),
  admin.database().ref(`users/${userId2}`).once('value'),
];

return Promise.all(records).then(snapshots => {
   const record1 = snapshots[0].val();
   const record2 = snapshots[1].val();
});
Allen
  • 350
  • 2
  • 13