如何基于来自承诺的动态响应构建 Firestore 查询链 [英] How to build a Firestore query chain based on a dynamic response from a promise

查看:17
本文介绍了如何基于来自承诺的动态响应构建 Firestore 查询链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我需要针对我在承诺中收到的主题集合查询 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 并在此基础上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.

要使用它,您的文档需要包含一个数组 subjects,例如:

To use this you documents will need to contain an array subjects, like:

subjects: ['Math', 'Biology']

然后你会查询它:

var query = firebase.firestore().collection("bla")
  .where('subjects', 'array-contains-any', ['Math', 'Science', 'History']);
query.get()...

这篇关于如何基于来自承诺的动态响应构建 Firestore 查询链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆