【问题标题】:Deleting docs in a collection using Angular in Firestore在 Firestore 中使用 Angular 删除集合中的文档
【发布时间】:2018-05-05 10:55:55
【问题描述】:

我正在尝试使用 Angular 在 Firebase 中的 Firestore 中的文档内的集合中删除文档及其嵌套文档。截至目前,我可以删除所述文档和集合,但编译器不会向我抛出错误error TS2339: Property 'id' does not exist on type '{}'。错误代码可能是对还是错,我真的不知道,因为我的代码确实找到了与我正在查看的对象关联的 id。这是我的代码:

testID: string;
private testDoc: AngularFirestoreDocument<Test>;

constructor(private db: AngularFirestore) { }

deleteDoc() {
    console.log('Deleting test');
    this.db.collection(`tests/${this.testID}/questions`, ref => ref.orderBy('order'))
        .valueChanges().subscribe(questions => {
            questions.map(question => {
                this.db.doc(`tests/${this.testID}/questions/${question.id}`).delete()
                    .catch(error => {console.log(error); })
                    .then(() => console.log(`tests/${this.testID}/questions/${question.id}`));
            });
        });
        this.testDoc.delete().catch(error => console.log(error));
    }

我也尝试在 map 函数中传递 2 个参数,但这只会在执行的函数而不是编译器中引发错误,从而使代码根本不起作用(我可能没有在这里传递正确的东西)。

正如我所提到的,我的代码有效,但我肯定做错了什么。所以我的问题是,我做错了什么来触发编译错误,如何在确保函数仍然有效的同时避免这种情况?希望有人可以帮助澄清我在这里做错了什么。

提前谢谢你。

*编辑,包括我正在查看的文档

export interface Question {
    description: string;
    order: number;
    type: string;
    id: string;
    name: string;
    options?: Object[];
    radio_amount?: number;
    current_chips?: Object[];
    imageURL?: string;
}

【问题讨论】:

  • 您的question.id 是否有 id 字段或者您期待密钥?
  • 它有字段 id 我相信是的。我已更新问题以包含我正在查看的内容。
  • 这部分代码在做什么this.testDoc.delete()
  • 测试是主文档,问题是嵌套在主文档下的集合中的子文档。它正在删除带有问题的嵌套集合的文档。但是,删除文档不会删除嵌套集合。
  • 看起来你刚刚声明了它,没有分配任何东西。那么删除是如何工作的呢?

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


【解决方案1】:

我想我错过了我正在查看的变量的类型,但是我不知道如何在箭头函数中声明该变量的类型,因为试图将外部变量包含到函数中对我不起作用.

我通过添加在此处的代码中看到的类型来修复我的错误。现在代码就像以前一样工作并且它不会给我一个编译器错误。

deleteDoc() {
    this.db.collection(`tests/${this.testID}/questions`,
        ref => ref.orderBy('order')).valueChanges().subscribe(questions => {
        questions.map((question: Question) => {
            this.db.doc(`tests/${this.testID}/questions/${question.id}`).delete()
                .catch(error => {console.log(error); })
                .then(() => console.log(`Deleting question (${question.id}) in (${this.testID})`));
        });
    });
    this.testDoc.delete().catch(error => console.log(error)).then(() => console.log(`${this.testID} has been deleted.`));
}

感谢你们中的一些人试图给我的帮助,但你们似乎更关注我的代码无法正常工作的事实,而事实并非如此或问题所在。重点是我在编译器抛出的问题中指定的错误,尽管函数正常工作,以及如何正确编写代码以不抛出错误。

请注意,我不建议使用上述函数,因为它当前在订阅问题集合时正在运行,因此当我在函数期间删除文档时值发生变化时,它还会多次运行代码.它可以工作,但没有优化。

【讨论】:

    猜你喜欢
    • 2018-03-22
    • 2018-05-11
    • 2020-09-08
    • 2018-07-20
    • 2020-02-17
    • 2018-11-01
    • 2019-04-04
    相关资源
    最近更新 更多