how can get data from firestore two collections and merge all data together

Viewed 622

first I tried to get data from the leaderboards collection and then I tried to get users details
and add data into winnerlist array but it doesn't work as I want.

  1. winnerlist order is not correct
  2. return res.send({ winnerList: result }); part also not working

what is the best way to do this? what I'm doing wrong here? I'm kinda new to this plz help me what I'm expecting is winnerlist array with all users' details and the correct order.

const leaderboardsCollectionRef = db.collection('leaderboards');
  const usersCollectionRef = db.collection('users');
  const winnerList = [];


  const promise1 = new Promise((resolve, reject) => {
    leaderboardsCollectionRef.orderBy('weeklyPoints', 'desc').limit(13).get().then(async results => {

      results.forEach(async doc => {
        return new Promise((resolve, reject) => {
          const users = usersCollectionRef.where("uid", "==", doc.id).get().then(async snapshot => {

           snapshot.forEach(async doc => {
              winnerList.push({
                [doc.id]: doc.data()
              });
            });
            resolve(winnerList);
          }).catch(err => {
            functions.logger.error('ERR =>', err);
            reject(err);
          });
        });
      });
    }).catch(err => {
      functions.logger.error('ERR =>', err);
      reject(err);
    });

  });

  Promise.all([promise1])
    .then((result) => {
      console.log('result', result)
      return res.send({
        winnerList: result
      });
    }).catch(err => {
      functions.logger.error('ERR =>', err);
    });
1 Answers

Assuming you'll wrap this in an async function, I guess this will work:

const leaderboardsRef = db.collection('leaderboards');
const usersCollectionRef = db.collection('users');
const winnerList = [];

const resultsQuery = leaderboardsRef.orderBy('weeklyPoints', 'desc').limit(13);
const resultsSnapshot = await resultsQuery.get();

const uids = [];
resultsSnapshot.forEach(doc => {
    uids.push(doc.id);
});

for (const uid of uids) {
    const userRef = usersCollectionRef.doc(uid);
    const userSnapshot = await userRef.get();
    winnerList.push({ [uid]: userSnapshot.data() });
}

res.send({ winnerList });
Related