【问题标题】:how to get the ID of a sub collection in Firestore HTML?如何在 Firestore HTML 中获取子集合的 ID?
【发布时间】:2021-06-06 15:28:05
【问题描述】:

我创建了一个集合名称(“用户”),并在其中创建了 subCollection(“innerGuides”)。我知道如何从主集合(“用户”)中检索数据,但我想知道如何获取子集合的 ID(“innerGuides”)。

db.collection("users").doc(user.uid).collection("innerGuides").doc("BGP9O0Rh2ThiL40tXOVG").get().then(doc => {
    console.log(user.uid);
    console.log(doc.data().content);
  }).catch(error => {
    console.log(error);
  })

如您所见,我可以通过“user.uid”检索我的主集合 UID,但对于我的 subCollection,我如何检索它的“uid”。我已经输入了 subCollection uid,但是如何动态检索它。

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    从您的示例中获取 DocumentSnapshot 的 id 是:

    db.collection("users").doc(user.uid).collection("innerGuides").doc("BGP9O0Rh2ThiL40tXOVG").get().then(doc => {
        console.log(doc.id);  // <-- here
        console.log(doc.data().content);
      }).catch(error => {
        console.log(error);
      })
    

    您也可以使用doc.exists 来查看您的get() 的文档是否真的存在。

    要查看带有 id 的文档,例如:

    console.log({
      id: doc.id,
      ...doc.data(),
    });
    

    子集合的 id 类似于:users/the-user-id/innerGuides/BGP9O0Rh2ThiL40tXOVG。没有办法只返回BGP9O0Rh2ThiL40tXOVG,因为它本身并不是一个完整的参考。如果您需要该值,请将其从 id 中解析出来。 JavaScript 有很多方法可以做到这一点。我脑海中浮现的一个是 split():

    const subId = id.split('/')[3]
    

    可能最好先验证数组,等等,但它会在成功时为您提供 id。

    【讨论】:

    • 你的回答有点正确,但我想从我的 subCollection 中检索数据,因为你可以看到我有一个对主集合 ID(“user.uid”)的引用,但我如何创建一个 ref到我的子集合 ID
    • 在您的示例中,BGP9O0Rh2ThiL40tXOVG 不是您的子集合 ID 吗?也许我不明白你要做什么。
    • 是的,你是对的.....'BGP9O0Rh2ThiL40tXOVG'是我的 subCollection ID,但正如你所见,我自己输入了 ID,但我想将此 ID 存储到 const... 如何这样做?
    • 为了澄清,当前的 id 看起来像 users/the-user-id/innerGuides/BGP9O0Rh2ThiL40tXOVG?
    猜你喜欢
    • 1970-01-01
    • 2022-07-08
    • 1970-01-01
    • 2021-05-26
    • 2019-10-03
    • 2021-07-12
    • 2019-09-24
    • 2021-01-15
    • 1970-01-01
    相关资源
    最近更新 更多