【问题标题】:Firebase: Using async/await syntax, how can I capture the firestore doc id?Firebase:使用 async/await 语法,如何捕获 firestore doc id?
【发布时间】:2021-01-23 17:59:37
【问题描述】:

希望这不是太难解决。

TLDR; 主要问题是如何使用async/await 而不是then() 语法。更具体地说,如何访问已访问文档的 docRef 以返回该文档的 id 以及所有其他数据?


我有一系列从我的 firestore 数据库中检索到的单词对象。

每个单词都是一个如下所示的对象:{word: 'Apple', ref: 9IOGPbdfoURivbNfffwF, points: 10}

我遍历这些单词中的每一个以捕获它们的完整细分,在ref 的目的地提供。这些词中的每一个都可能包含或不包含translations 子集合。


不幸的是,虽然我可以成功返回wordData,但该文档包含单词的 ID。相反,我需要的 ID 是 word 文档本身的 ID。我该如何写这个,所以我有一个 word 对象,它包含所有单词 data + 使用 async/await 语法的文档的 ID?

const data = Promise.all(
      vocab.map(async (word: Word) => {
        const wordRef = await word.ref.get();
        const wordData = await wordRef.data();     <-- Problem is here.
 
        const docRef = firebaseFirestore
          .collection(`languages/${language}/vocabulary`)
          .doc(wordData.id)                        <-- What i'm trying to do, but id isn't there
          .collection('translations')
          .doc(translationLanguage);
    ...
)

谢谢!

【问题讨论】:

    标签: javascript firebase google-cloud-firestore async-await


    【解决方案1】:

    data() 只返回文档中的字段。它不返回 ID。您已经拥有word.ref 中的文档 ID。

    const id = word.ref.id;
    

    另外,没有必要将awaitdata() 一起使用,因为它不会返回承诺。

    【讨论】:

      猜你喜欢
      • 2021-10-30
      • 2020-02-02
      • 2021-09-25
      • 2021-06-20
      • 2020-09-07
      • 2017-04-14
      • 1970-01-01
      • 2016-02-07
      • 2020-06-02
      相关资源
      最近更新 更多