在Firestore中按类型为“引用"的字段进行查询 [英] Querying by a field with type 'reference' in Firestore
问题描述
我有一个名为类别"的集合,其中包含一个ID为5gF5FqRPvdroRF8isOwd的文档.
I have a collection called 'categories' containing a single document with ID: 5gF5FqRPvdroRF8isOwd.
我还有另一个收藏集,叫做门票".每张票证都有一个参考字段,用于将票证分配到特定类别.
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中按类型为“引用"的字段进行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!