Home > Software design >  Is it possible to store a user id as the key of a field in a Firestore document?
Is it possible to store a user id as the key of a field in a Firestore document?

Time:05-16

So I saw this in the "Get to know Firestore" youtube series from the official Firebase channel, where they used a userId as the key of a field. However, I can't seem to recreate this in my project using "firebase": "^9.6.6", and angular 13.0.4.

private async addMemberToGroupDetail(groupId: string) {
const groupRef = doc(this.firestore, 'groupDetail', groupId);
const userId = this.authService.userId;
updateDoc(groupRef, {
     roles: {
       `${userId}`: 'member',
     },
});

}

Error: Property assignment expected.

CodePudding user response:

Give this syntax a shot:

updateDoc(groupRef, {
     roles: {
       [`${userId}`]: 'member',
     },
});

Might just need those square brackets as assigning the key dynamically.

As @Frank added in comments, if you don't need to convert to string, you can just do:

[userId]: 'member'
  • Related