How to read data of multiple user id in a single request in cloud functions on firebase

时间:2017-08-05 12:11:08

标签: node.js firebase firebase-realtime-database firebase-admin

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 ?

2 个答案:

答案 0 :(得分: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
})

答案 1 :(得分:3)

这可以写得更清洁:

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();
});