How to Convert Firebase Querysnapshots to an Array of objects

Viewed 1008

I am trying to return selected teams from a collection of teams. It seems like I need to convert the snapshot to the Team object. How do I do that? Is there an easier way to convert a snapshot into an array? I am new to firebase/angular so hopefully I am missing something simple.

using angular 5.5.2

export class Team {
    internalTeamName: string;
    externalTeamName: string;
    creatorNumber: number;
    teamAdmins: TeamMember[];
    teamMembers: TeamMember[];
    constructor(code ommitted)
}

service.module

loadTeams(email){
const teamArray: Team[] = null;
this.firestore.collection('teams', ref => ref.where('teamAdmins', 'array-contains', email))
.get()
.forEach(function(childSnapshot) { 
teamArray.push(childSnapshot);})
.then(
   return teamArray )
.catch(
  err => console.log(err)
)

The error from the above code: Argument of type 'QuerySnapshot' is not assignable to parameter of type 'Team'. Type 'QuerySnapshot' is missing the following properties from type 'Team': internalTeamName, externalTeamName, creatorNumber, teamAdmins, teamMembers

function calling the above function: What is the best practice when calling service functions?

public teamArray: Team[] = null;

ngOnInit() {
this.teamArray = this.teamCrudService.loadTeams(this.authService.email);
}
2 Answers

How to Convert a querySnapshot into an Array on (at least) Firebase 9+

TL;DR: Try using querySnapshot.docs.map(doc => doc.data())

Example usage:

async function getUsers() {
  let querySnapshot = await getDocs(collection(db, 'users'))
  return querySnapshot.docs.map(doc => doc.data())
}

querySnapshot.docs returns an array of documentSnapshot objects, and those have a .data() method that returns the real values you're looking for.

So far from what I've read, in their docs they showcase that you can use querySnapshot.forEach(doc => {etc.}) but I haven't seen them show the method I mentioned.

Related