Search code examples
arraystypescriptgoogle-cloud-firestoreangularfire2angularfire

AngularFire2: Create document and set an array of maps


Requested behaviour:
I would like to create an AngularService which adds a document to Firestore with two fields. The first field is a map which is filled with user data. The second field is an array of maps. It should receive the map from the first field as the first item.

Current State
The function creates and fills the document successfully if I only add the map (first field) and comment out the array of maps(second field).

issue
If I add code for setting the array, the function does not work anymore. I receive the following error even both fields are called with the same data:

FirebaseError: Function DocumentReference.set() called with invalid data. Unsupported field value: undefined (found in field groupExecutiveBoard)

How can I fix that? How can I create the array of maps and push the first map to it?

My Model:

export interface Group {

    groupLeader?: {
        groupLeaderID?: string;
        groupLeaderName?: string;
        groupLeaderImage?: string;
    };
    
    //array
    groupExecutiveBoard?: {
        boardMemberID?: string;
        boardMemberName?: string;
        boardMemberImage?: string;
    }[];
    
}

My Service

constructor(private angularFirestore: AngularFirestore) { }

addGroup(author: User) {
  const groupsCollection = this.angularFirestore.collection<GroupID>('groups');

  groupsCollection.add({

    // sets groupleader if "GroupExecutiveBoard" is commented out
    groupLeader: {
      groupLeaderID: author.uid,
      groupLeaderName: author.displayName,
      groupLeaderImage: author.profilePhoto
    },

    //should set user data as first array item. Does not work
    groupExecutiveBoard: {
      boardMemberId: author.uid,
      boardMemberName: author.displayName,
      boardMemberImage: author.profilePhoto
    }[0],

  });
}


Solution

  • Try this out:

    groupLeader: {
          groupLeaderID: author.uid,
          groupLeaderName: author.displayName,
          groupLeaderImage: author.profilePhoto
        },
    groupExecutiveBoard: [{
          boardMemberId: author.uid,
          boardMemberName: author.displayName,
          boardMemberImage: author.profilePhoto
    }],