【问题标题】:Angular Firebase - How to add a property to document in firestore?Angular Firebase - 如何将属性添加到firestore中的文档?
【发布时间】:2019-06-03 06:21:25
【问题描述】:

我对 Angular Firebase 解决方案有疑问。

我想要做的是将一个属性添加到已经存在于 firestore 文档中。

我的用户界面看起来像这样

export interface User {
    email: string;
    uid: string;
    photoURL?: string;
    displayName?: string;
    teams?: string[];
}

我想创建一个团队并将该团队 ID 添加到现有用户对象中的 teams 数组中。

我不想获取所有用户数据,只是为该字段添加一个新值。

这可能吗?也许您对如何更有效地做到这一点有一些建议?

团队界面是这样的

export interface Team {
    name: string;
    description?: string;
    admin?: string; // = creator - first user
    members?: string[]; // array of users UIDs.
    boards?: string[]; // array of board docs id.
} 

负责添加团队的组件只是一个表单,所以 `onSubmit()' 我尝试执行以下操作,但我不知道如何将该团队文档 ID 放入用户对象。

onSubmit(form: NgForm) {
    const newTeam: Team = {
        name: form.value.name,
        description: form.value.description,
        admin: this.auth.currentUserId,
        members: [this.auth.currentUserId],
    };
    const userRef: AngularFirestoreDocument<any> = this.afs.doc(
        `users/${this.auth.currentUserId}`
    );
    let teamRefId = '';
    this.afs.collection('teams').add(newTeam).then((docRef) => teamRefId = docRef.id);
    this.router.navigateByUrl('/dash');
}

有什么想法吗?也许这应该是某种传播运算符,但我不想再一次获取用户对象并将其发布回 Firestore,而只是更新该字段...

【问题讨论】:

    标签: angular typescript firebase google-cloud-firestore angularfire2


    【解决方案1】:

    您可以通过使用以下内容更新文档来做到这一点:

    let teamArray = []; // if not excisting.
    teamArray.push(teamRefId); // or just add it if it's.
    userRef.update({teams: teamArray});
    

    更新不会改变除了团队之外的其他任何东西。如果团队不存在,则会添加团队。

    【讨论】:

    • 好的,但我希望用户拥有多个团队。那么它会为团队数组添加一个值还是只更新一个?
    • 那你得先让这个用户的所有团队,把团队添加到已经存在的数组中。查看我的编辑。
    • 如果要查询数组可以使用array-contains
    猜你喜欢
    • 1970-01-01
    • 2020-03-03
    • 2018-05-10
    • 1970-01-01
    • 2020-01-05
    • 2018-07-26
    • 1970-01-01
    • 2019-06-04
    • 2012-07-18
    相关资源
    最近更新 更多