问题描述
我有一个名为类别"的集合,其中包含一个 ID 为 5gF5FqRPvdroRF8isOwd 的文档.
I have a collection called 'categories' containing a single document with ID: 5gF5FqRPvdroRF8isOwd.
我还有一个名为tickets"的集合.每张票都有一个参考字段,用于将票分配给特定类别.
I have another collection called 'tickets'. Each ticket has a reference field which assigns the ticket to a particular category.
门票集合中的字段称为类别",字段类型为reference
.
The field in the tickets collection is called 'category' and has a field type of reference
.
在下面的代码中,categoryDocId
是我要查询的类别的文档ID.
In the code below, categoryDocId
is the document ID of the category I want to query by.
const categoryDocID = `5gF5FqRPvdroRF8isOwd`;
const files = await firebase
.firestore()
.collection('tickets')
.where('category', '==', categoryDocID)
.get();
为什么 files.length
返回 0?
为了测试,我将 category
字段类型更改为字符串,并将其设置为类别 ID 而不是直接引用.这正确返回了分配给该类别的票证,这让我相信这与我如何查询 reference
字段有关.
For testing, I changed the category
field type to string, and set it to the category ID instead of a direct reference. This correctly returned tickets assigned to the category, which leads me to believe it's something about how I'm querying a reference
field.
推荐答案
As you will read here in the doc, the Reference Data Type is used to store DocumentReferences.
如果要在查询中使用,不能使用简单的字符串,既不能是文档的UID(即'5gF5FqRPvdroRF8isOwd'
),也不能是字段中存储的字符串值(即'/categories/5gF5FqRPvdroRF8isOwd'
).
If you want to use it in a query, you cannot use a simple string, neither the UID of the document (i.e. '5gF5FqRPvdroRF8isOwd'
), nor the string value that is stored in the field (i.e. '/categories/5gF5FqRPvdroRF8isOwd'
).
您必须构建一个 DocumentReference 并在您的查询中使用它,如下所示:
You have to build a DocumentReference and use it in your query, as follows:
const categoryDocRef = firebase.firestore()
.collection('categories')
.doc('5gF5FqRPvdroRF8isOwd');
const files = await firebase
.firestore()
.collection('tickets')
.where('category', '==', categoryDocRef)
.get();
这篇关于通过 Firestore 中类型为“reference"的字段进行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!