Daniel
October 30, 2020
Recently we started moving some of our services to use Google Cloud Functions. During the move, we decided to try out Google Firestore for our database. Firestore is a serverless NoSQL document database provided by Google. It is fully managed and can be easily scaled to meet our needs. Our serverless functions are currently written in Node.js, so this post will refer to the server client libraries for Node.js.
Firstly we need to install Firestore into our project. We can do this using npm:
Then we can simply use the library to initialise Firestore:
We can now use the Firestore API to add, update, query and remove data from Firestore.
To add a document to Firestore we can use the following:
Using the 'add' function will add a document to the collection, an ID for the document will be set by Firestore. If we want to set the document ID ourselves we can use:
The ID of our document will now be 'fiat'. We update and retrieve it using the same name.
Now that we have an example of putting in a document, we need to get it back out. Firstly we'll assume we know the documents ID:
If we do not know the ID of the document, we can query for the document or retrieve all documents in the collection. Firstly we will get all of the documents in the collection.
This will return the whole collection, we could then filter or iterate of these documents to get the result we want.
We can also query for documents that match a query.
This will return a query snapshot that contains a callback to a sorted array for documents matching this query.
To delete a document in a collection we can do '.delete()' on the document:
We can also combine this with our query to retrieve and delete documents that contain (or don't) certain information.
Something changes and we need to add a field to our document. We can do this using the '.set()' method on a document:
We use the {merge} option to merge the fields in the two documents. The document will remain the same but be updated with the new 'speed' field.
We can replace the whole document by omitting the {merge} option.
Testing Firestore is made really easy using the Firestore emulator. This will start a local Firestore instance to test against. This can be run using the following command:
As we haven't given it a port it will start on localhost:8080.
In the unit tests (using AVA in this case) we can set up the use of Firestore in the before:
We can now use Firestore as if we were using it in production in our tests.
We have covered the basic operations to get started with Google Firestore. There are many more operations to learn such as transactions, sub collections and more advanced queries. You can get started with these by using the official docs found here.
I am a Software Engineer working as part of the nerd.vision team, mainly working on the backend systems and agents. When I'm not squashing bugs, I enjoy travelling, gaming and experiencing new foods and cultures.