Get updates on your email

Wednesday, November 7, 2018

Firestore CRUD functionalities

This is possibly the simplest implementation of CRUD functionality of firestore.

Create a collection called user and leave the Document ID and blank add fields, their types and values:

I've a collection named as Users and I'll share how you can first save, retrieve and then update totalGamesPlayed

The visible data in this photo is showing totalGamesPlayed is 40

Before we dive into storing it is important to match that you have the same rules for database as I have:

In you XCode project make sure you have installed the pod for firestore:
pod 'Firebase/Core'
pod 'Firebase/Firestore'

Also I've installed pod 'Firebase/Auth' too as I've implemented login with google on the app that I'm using as an example.

On top import this:

import FirebaseFirestore

Add New Data to Firestore:

let userCollection = Firestore.firestore().collection("Users")
                var userObj: [String: Any] {
                    return ["userID": "12345",
                            "email": "",
                            "fullName": "Chaudhry Talha",
                            "totalGamesPlayed": totalGamesPlayed ,

                userCollection.addDocument(data: userObj)

Here the totalGamesPlayed is just an Int that I'll be storing. Doing so will save the data into the database.

Retrieve or Get Data from Firestore:

This has two sub-parts:

  • Get all the users
  • Get users based on a filter

Before we start implementing them there is a common part that both of them will use. This is the basic settings before we start retrieving:

let db: Firestore = Firestore.firestore()
let settings = db.settings
settings.areTimestampsInSnapshotsEnabled = true
db.settings = settings

Get all the users

        db.collection("Users").getDocuments { (snapshot, error) in
            if let err = error {
                print("Error: \(err)")
            } else {
                for document in snapshot!.documents {
                    let totalGPlay = document.get("totalGamesPlayed") as! Int
                        print("Total Game Played: \(totalGPlay)")
                    //print( //this is a Dictionary. Uncomment this to get the full retrieved document

Our db is calling the Users collection to perform getDocuments. If there is no error we are running a for loop on all the documents that were retrieved. Then we are storing and printing just totalGamesPlayed. As in first screenshot we have just two entries so it retrieved two documents and printed it successfully.

Get users based on a filter

If you want to filter the getDocuments you have to add a query after the db.settings = settings line.

var query: Query

query = db.collection("Users").whereField("totalGamesPlayed", isEqualTo: 40)

The best scenerio would be to add this filter on a unique field like email to get all the entries for that specific email address.

query.getDocuments { (snapshot, error) in
            if let err = error {
                print("Error:  \(err)")
            } else {
                for document in snapshot!.documents {
                    let totalGPlay = document.get("totalGamesPlayed") as! Int
                    print("Ttal Game Played: \(totalGPlay)")
                    //print( //uncomment to print the full document


This is same as getting all users but here instead of applying getDocuments function on all the database (db) collection we are just applying it on a query and this just gave us one document as there is only entry where total games played is 40.

Update a specific Document

There can be number of ways to update a record but the one I choose is serving the purpose of my project i.e. Get user based on a filter (which will be always one) and then get the unique autoID (Document ID) and update that record.

var query: Query

        query = db.collection("Users").whereField("email", isEqualTo: "")

Same thing but changed the query to get user by a specific email.

query.getDocuments { (snapshot, error) in
            if let err = error {
                print("Error: \(err)")
            } else {
                    let docID = snapshot!.documents.first?.documentID
                    db.collection("Users").document(docID!).setData([ "totalGamesPlayed": 333 ], merge: true)


get document based on the query and if there is no error get the documentID for the first document in snapshot documents. Finally go to Users collection where document id is docID and setData (which means change data) of key total games played to 333.

This will successfully update your record by overwriting.

No comments:

Post a Comment