Efan Du
Efan Du

Reputation: 123

Angular Firestore Get Single Document With Query

I'm using Google Firestore. There is a collection called Universities, where each document represents a university.

How do I find a university by its name and update its view_count by +1?

[Collection: Universities]:
  [Document: 0JsaLtcfdDaEtHLMlMrh]:{
                      name: The University of Sydney,
                      view_count: 1
            };
   [Document: K2z7DMhKreyDniGUpo2t]:{
                      name: University of New South Wales,
                      view_count: 2
            }

Upvotes: 2

Views: 7476

Answers (1)

Shantanu
Shantanu

Reputation: 3513

You can do something like this:

db.collection("Universities").where("name", "==", "The University of Sydney")
    .get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            // doc.data() is never undefined for query doc snapshots
            //console.log(doc.id, " => ", doc.data());
            var docData = doc.data();
            var updatedCount = docData.view_count + 1;
            var universityRef = db.collection('Universities').doc(doc.id);
            var setWithMerge = universityRef.set({
                                    view_count: updatedCount
                                }, { merge: true });

        });
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });

So, here what you can do is first query in collection using where to get all docs with specific name, then inside querySnapshot you'll get one doc object & then you can create reference of that document & update (overwrite) its view_count property value using set method with merge: true to keep other property values as it's.

Follow offcial docs: Add data, Get data

Note: This's generic web JS solution. You can use same logic & write typescript code in angular app

Upvotes: 5

Related Questions