【问题标题】:"documentRef" is not a valid DocumentReference showing“documentRef”不是显示的有效 DocumentReference
【发布时间】:2021-12-04 16:17:23
【问题描述】:
async function process_tasks() {
    let campaignsRef = db.collection('campaigns')
    let activeRef = await campaignsRef.where('active', '==', true).select().get();
    for (campaign of activeRef.docs) {
        console.log(campaign.id);
        (CHOICE 1) let tasksRef = await campaignsRef.doc(campaign.id).collection('tasks').get();
        (CHOICE 2) let tasksRef = await campaign.collection('tasks').get();
        for(task of tasksRef.docs) {
            console.log(task.id, task.data())
        } 
    }
}

当我使用 (CHOICE 2) 时,"documentRef" 不是有效的 DocumentReference 错误显示。
我的代码中没有名为 documentRef 的变量(作为对那些的注释评论错误的人)

我想知道为什么? campaign 不应该等于 campaignsRef.doc(campaign.id)

【问题讨论】:

  • 您的代码中没有变量documentRef(如错误中所述)。您确定错误来自此代码吗?
  • 变量documentRef在哪里?你能发布整个错误吗?
  • 据我所知campaigndocumentRef。我认为你不能在documentRef 上使用.collection。 @FrankvanPuffelen
  • 错误消息说有一个名为documentRef 的变量应该是DocumentReference 类型。该代码没有名为documentRef 的变量,因此是我的问题。
  • @FrankvanPuffelen 我可以知道为什么你认为我的代码有一个名为 documentRef 的变量吗?

标签: javascript firebase google-cloud-firestore


【解决方案1】:

你在第二次选举中写的一切都是正确的,除了一件事。在 for 循环中创建的变量(campaign)是 DocumentSnapshot。您必须使用 .ref 访问来自 DocumentSnapshot 的参考。

async function process_tasks() {
    let campaignsRef = db.collection('campaigns')
    let activeRef = await campaignsRef.where('active', '==', true).select().get();
    for (campaign of activeRef.docs) {
    //campaign is DocumentSnapshot
        console.log(campaign.id);
        (CHOICE 1) let tasksRef = await campaignsRef.doc(campaign.id).collection('tasks').get();
        (CHOICE 2) let tasksRef = await campaign.ref.collection('tasks').get(); // add .ref after campaign
        for(task of tasksRef.docs) {
            console.log(task.id, task.data())
        } 
    }
}

谢谢。

【讨论】:

  • 所以 campaign 是一个 DocumentSnapshot,它是一个 documentref 。我们必须进一步使用.ref 来获取DocumentReference
  • 完全正确,您应该使用 .ref 从 DocumentSnapshot 获取 DocumentReference。例如:var documentSnapshot = db.collection("campaign")。 doc(...).get(); var documentReference = documentSnapshot.ref;
  • 你是stackoverflow中的英雄......这有记录吗?我只是在 Firestore 文档中找不到...
猜你喜欢
  • 1970-01-01
  • 2021-07-30
  • 1970-01-01
  • 1970-01-01
  • 2022-06-22
  • 2022-02-25
  • 2023-02-05
  • 1970-01-01
  • 2013-08-22
相关资源
最近更新 更多