user12584812
user12584812

Reputation:

How can i get each user data for multiple user in every team that i got in firebase (node.js)

I got a function written in NODE.JS on firebase that gives me the details for all the teams, where logged user is assigned to:

exports.getTeams = (req, res) => {
let teams = [];
db
    .collection("teams")
    .where("members", "array-contains" , req.user.user_id)
    .get()
    .then((data) => {
        data.forEach((doc) => {
            teams.push({
                teamId: doc.id,
                createdAt: doc.data().createdAt,
                leadId: doc.data().leadId,
                members: doc.data().members,
                name: doc.data().name 
            });
        });
        return res.status(200).json(teams);
    })
    .catch(err => {
        res.status(500).json({error: err.code})
    })
}

A 'members' is an array with every userId - those ids are unique ids by which we can filter. In this case:

[uETl8OOisUQLRtmCHoOdy1bsQvf1, QOfg07fDa1X63ao30fq3vqUSU5f2]

How could I get the details for every user in this array such as first&last name, email, etc. As far as I know, I should return a promise with the users, but how to assign them respectively to the correct teams.

Sample users collection: enter image description here

Sample teams collection: enter image description here

Error code: enter image description here

Upvotes: 0

Views: 75

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50890

It looks like you want to:

  1. Get all the teams a user is part of.
  2. All the members of those teams
exports.getTeams = async (req: any, res: any) => {
  // QuerySnapshot of documents which matched the condition
  const teamsSnap = await admin.firestore().collection("teams").where("members", "array-contains", req.user.user_id).get()
  // Array containing data about all teams
  const teams = teamsSnap.docs.map((team) => ({
    teamId: team.id,
    createdAt: team.data().createdAt,
    leadId: team.data().leadId,
    members: team.data().members,
    name: team.data().name
  }))
   
  // Getting all member IDs by running a lot on teams array above
  // and creating a single array of all memberIds
  let memberIds = []
  teams.forEach((team) => {
    team.forEach((member) => {
      if (!memberIds.includes(member)) memberIds.push(member)
    })
  })

  // Request members' documents
  const requests = memberIds.map(m => admin.firestore().collection("users").doc(m).get())

  // If IDs of document ID are not same as user's UID and
  // the UID is present in the document as a field 'userId',
  // then change your query to this:
  const requests = memberIds.map(m => admin.firestore().collection("users").where("userId", "==", m).get())
  // You also need to access `docs[0]` in the map method below.

  // Array of DocumentSnapshots
  const membersSnap = await Promise.all(requests)
  // Array of User documents
  const memberDocs = membersSnap.map((m) => m.data())

  //const memberDocs = membersSnap.map((m) => m.docs[0].data())

  /* Parse your data here */ 

  return res.status(200).json(teams);
}

I just made a small assumption that all member documents are in a collection "users" but make sure you replace it. After you have all memberDocs, parse/filter them and return the necessary data to client.

Additionally, you might want to remove duplicates from the memberIds array as if you have same member in many teams, it'll end up fetching their documents that many times.

Edit:

I ran the code above and got this:

enter image description here

The first one is undefined because I had not document with key u0.

Upvotes: 0

Related Questions