Rajesh K
Rajesh K

Reputation: 713

How to use Query in Firebase Firestore

I am using Firebase function and Firebase Firestore to develope an API which will store users data.

I wanted to locate the documents using the properties stored in their field. This is the Firebase document which states how to achieve the same.

// Create a reference to the cities collection
var citiesRef = db.collection('cities');

// Create a query against the collection
var queryRef = citiesRef.where('state', '==', 'CA');

I wanted to handle two situations

  1. Where there is no document with the present conditions

  2. Where there are more than two documents with the present conditions

How could the above two situation be handled?

Upvotes: 0

Views: 1347

Answers (2)

basickarl
basickarl

Reputation: 40561

The accepted answer does not show how to extract the data from each document and imo is only half the answer. the following will get you iterating through every document and extracting the data.

db.collection("cities").get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        // doc.data() is never undefined for query doc snapshots
        console.log(doc.id, " => ", doc.data());
    });
});

Upvotes: 1

Renaud Tarnec
Renaud Tarnec

Reputation: 83191

Following our "discussion" in the comments above, in a Cloud Function you could do as follows, using the QuerySnapshot returned by the get() method:

admin.firestore().collection("cities")
    .where('state', '==', 'CA')
    .get()
    .then(querySnapshot => {
        if (querySnapshot.size == 0) {
            console.log("0 documents");
        } else if (querySnapshot.size > 2) {
            console.log("More than 2 documents");
        } 
    });

As said, above, just be aware that this will cost a read for each document in the collection. In case you have a very large collection, you could write a Cloud Function that update a counter each time a doc is added/removed to/from the collection.

Upvotes: 2

Related Questions