如何在数组中获取Firestore收集响应? [英] How to get firestore collection response in an Array?

查看:34
本文介绍了如何在数组中获取Firestore收集响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在Cloud Firestore中查询时,有什么方法可以获取Array格式的响应?我知道两种方法,但我想知道是否还有其他直接链接到该方法的方法

Is there any way i can get the response in an Array format when i query in the cloud firestore? I know two ways but I want to know if there is any other way which is directly linked to that

const queryRef = await db.collection('xyz').where('time','==',29).get()
const array = []
queryRef.forEach(doc => {
    array.push(doc.data())
})

还有其他类似的方法.

 const array2 = queryRef.docs.map(doc => doc.data());

有没有办法获得相同的响应而无需使用外部javascript方法?如果可能的话,如何计算满足查询条件的响应数像

Is there any way to get the same response without using external javascript methods and if possible how can i count the number of response which is satisfying the queries like

const queryRef = await db.collection('xyz').where('time','==',29).get()

在执行或将其存储在数组中之前,我不知道在此查询中可以获得多少文档

I don't know how many documents i get in this query untill i perform or store that in an array

推荐答案

您显示的代码均未使用外部javascript方法".您显示的foreach循环和 map()都是非常标准的JavaScript,并且都同样有效.实际上,这是我使用Firestore查询结果时见过的两种最常见的方式.对我来说不清楚,为什么你需要一些不同的东西.

None of the code you're showing uses an "external javascript method". Both the foreach loop and the map() you're showing are very standard JavaScript and both equally valid. In fact, these are the two most common ways that I've seen for consuming Firestore query results. It's not clear to me why you need something different.

您在这里还有第二个问题,关于对使用 await 的查询的结果进行计数:

You have a second question here about counting results from a query using await:

const queryRef = await db.collection('xyz').where('time','==',29).get()

该代码具有误导性,因为该查询的结果不是引用.这是 QuerySnapshot .但是,如果您想要该对象的结果数量,只需访问结果文档数组即可:

That code is misleading because the result from that query is not a reference. It's a QuerySnapshot. But if you want the number of results from that object, just access the resulting document array:

const count = queryRef.docs.length

Firestore无法提供一种无需查询即可对文档进行计数的方法.没有像SQL中那样的聚合函数.如果您需要不带查询的文件计数,则在向集合中添加和删除文件时必须自己维护文件计数.

Firestore doesn't offer a way to count documents without making a query. There are no aggregate functions as in SQL. If you need a document count without a query, you're going to have to maintain a document count on your own as you add and remove documents to a collection.

这篇关于如何在数组中获取Firestore收集响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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