简体   繁体   中英

How to get firestore collection response in an 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())
})

there is other way also like this way.

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

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

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.

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

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

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM