首页 > 解决方案 > 从 ID 数组中查询 firestore 中的文档

问题描述

我想知道如何从一组 ID 的 firestore 集合中查询文档?我只想要集合中 ID 数组中的文档。我查看了另一个答案,认为我的方法是正确的,但是,我遇到了错误。

(node:15105) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'data' of undefined
>      at /Users/username/SideProjects/projectname/functions/index.js:40:38
>      at processTicksAndRejections (internal/process/task_queues.js:95:5)

发生错误是因为该函数未从该 ID 数组的集合中找到任何文档。但是,我仔细检查了数据库,并知道集合中有文档具有数组中的 ID。

const admin = require('firebase-admin')

....

let feedItems = db.collection(feedItemsCollection)

feedItemsList = feedItems.where(admin.firestore.FieldPath.documentId(), 'in', ['HPOorsSnbHpTYwwXxfWw']).get().then(snapshot2 => {
       console.log(admin.firestore.FieldPath.documentId())
       console.log("In feed Items")
       //console.log(feedItemIds)
       console.log(snapshot2[0])

       //error happens on this line because snapshot2[0] returns undefined
       console.log(snapshot2[0].data())
})

Snapshot2[0] 返回 undefined 我假设这意味着没有返回数据。我认为我没有正确调用 documentId(),但不知道解决方法。

标签: javascriptfirebasegoogle-cloud-firestorenosql

解决方案


您的代码“可能”存在两个问题。遵循这两点以确保一切正常

  1. 里面的数据snapshot2可能empty

你首先必须修复你的代码来测试这个理论。您没有snapshot2正确访问数据。要做到这一点,一种方法是:

// `snapshot2` will have a `docs` property that you can leverage
const snapshot2Data = snapshot2.docs.map((doc) => doc.data());
  1. .documentId()可能没有做它应该做的(如你所说)

为了检验这个理论,检查是否snapshot2Data为空。跑 :

console.log(snapshot2Data); // what do you get ?

如果不是,它不是空的并且你得到了数据,那么你就准备好了。无事可做

如果是,则为空,然后运行:

console.log(admin.firestore.FieldPath.documentId()); // what do you get ?

你回来了string吗?如果不是,那么我们还有另一个问题。您还需要仔细查看您的firebase-admin设置。


推荐阅读