通过 Firestore 中类型为“reference”的字段进行查询

新手上路,请多包涵

我有一个名为“类别”的集合,其中包含一个 ID 为:5gF5FqRPvdroRF8isOwd 的文档。

我还有另一个名为“门票”的收藏。每张票都有一个参考字段,将票分配给特定类别。

门票集合中的字段称为“类别”,字段类型为 reference

在下面的代码中, categoryDocId 是我要查询的类别的文档 ID。

 const categoryDocID = `5gF5FqRPvdroRF8isOwd`;

const files = await firebase
  .firestore()
  .collection('tickets')
  .where('category', '==', categoryDocID)
  .get();

为什么 files.length 返回0?

为了测试,我将 category 字段类型更改为字符串,并将其设置为类别 ID 而不是直接引用。这正确返回了分配给该类别的票证,这让我相信这是关于我查询 reference 字段的方式。

原文由 jskidd3 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 351
2 个回答

正如您将 文档中读到的那样,引用数据类型用于存储 DocumentReferences

如果要在查询中使用它,则不能使用简单的字符串,既不能是文档的 UID(即 '5gF5FqRPvdroRF8isOwd' ),也不能使用存储在字段中的字符串值(即 '/categories/5gF5FqRPvdroRF8isOwd' )。

您必须构建一个 DocumentReference 并在您的查询中使用它,如下所示:

JS SDK V9

 import { doc, query, collection, where, getDocs } from "firebase/firestore";

const categoryDocRef = doc(db, "categories", "5gF5FqRPvdroRF8isOwd");

const q = query(
  collection(db, "tickets"),
  where("category", "==", categoryDocRef)
);

const files = await getDocs(q);   // !! files is a QuerySnapshot

JS SDK V8

 const categoryDocRef = firebase.firestore()
   .collection('categories')
   .doc('5gF5FqRPvdroRF8isOwd');

const files = await firebase   // !! files is a QuerySnapshot
  .firestore()
  .collection('tickets')
  .where('category', '==', categoryDocRef)
  .get();

原文由 Renaud Tarnec 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用 Firebase 版本 9(2021 年 12 月更新):

您必须使用 “categories/5gF5FqRPvdroRF8isOwdand” 进行 文档引用,然后在您的查询中使用它:

 import { doc, query, collection, where, getDocs } from "firebase/firestore";

const categoryDocRef = doc(db, "5gF5FqRPvdroRF8isOwd");

const q = query(
  collection(db, "tickets"),
  where("category", "==", categoryDocRef)
);

const ticketDocsSnap = await getDocs(q);

原文由 Kai - Kazuya Ito 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题