如何基于Promise的动态响应构建Firestore查询链 [英] How to build a Firestore query chain based on a dynamic response from a promise
问题描述
比方说,我需要针对我在诺言中收到的一系列主题来查询Firestore:
Let's say I need to query Firestore against a collection of subjects that I receive in a promise:
const subjects: string[] = await getSubjects(); //response: ['Math', 'Science', 'History'];
由于我不知道在任何给定时间承诺中会返回多少主题,我将如何动态生成下面的链,以便正确查询Firestore?
Since I don't know how many subjects might be returned in the promise at any given time, how would I go about dynamically generating the chain below so I can properly query Firestore?
ref.where('subject[subjects[0].toLowerCase()]', '==' , true)
.where('subject[subjects[1].toLowerCase()]', '==' , true)
.where('subject[subjects[2].toLowerCase()]', '==' , true);
返回的主题越多,需要生成的 .where()
方法就越多.
The more subjects that are returned, the more .where()
methods it would need to generate.
推荐答案
创建查询遵循一个构建器模式:当您调用 where
时,它会返回一个 Query
,然后在该查询上查询
,您可以再次调用 where
.
Creating a Query follows a builder pattern: when you call where
it returns a Query
and on that Query
you can call where
again.
因此,如果您有一个主题数组并且想要创建一个主题查询,则可以执行以下操作:
So if you have an array of subjects and want to create a query of those, you can do:
var query = firebase.firestore().collection("bla");
['Math', 'Science', 'History'].forEach((subject) => {
query = query.where(`subject[${subject}.toLowerCase()]'`, '==' , true);
})
query.get()....
请注意,如今的Firestore支持 array-contains-any
运算符,该运算符的伸缩性明显好于这些类型的运算,并且一次可以处理多达10个主题.
Note that Firestore nowadays supports an array-contains-any
operator, which scale significantly better for these types of operations and can deal with up to 10 subjects at once.
要使用此功能,您的文档将需要包含一个数组 主题
,例如:
To use this you documents will need to contain an array subjects
, like:
subjects: ['Math', 'Biology']
然后使用以下命令进行查询:
And then you'd query it with:
var query = firebase.firestore().collection("bla")
.where('subjects', 'array-contains-any', ['Math', 'Science', 'History']);
query.get()...
这篇关于如何基于Promise的动态响应构建Firestore查询链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!