# Lesson 26 Firebase Data
# Storing Your Data in Firestore
We want to store data and retrieve it in our app, so lets get started.
Here is a link to the Google Cloud firestore documentation we are going to use.
Open up the documentation and use it as a resource when you need to know more or have questions.
Here is a list of Firestore videos, please watch the first one before proceeding, and then come back and watch the others when you need to know more.
Watch This Video
What is a NoSQL Database? How is Cloud Firestore structured? | Get to Know Cloud Firestore #1 15:28 Minute video
- Get to Know Cloud Firestore #1 NoSQL Database, Document Model.
- 0:40 Relational Databases used strict structures, multiple tables joined by foreign keys. Traditionally SQL Relational databases are used to guarantee data integrity, structure and reduce redundancy.
- 2:40 Firestore is NoSQL, schemaless.
- 4:20 Code defensively, there is no guarantee that the data will be in a structure you expect.
- 4:58 Separate calls for separate data, no SQL queries.
- 8:02 The advantage is that NoSQL is fast and easy.
- 8:44 NoSQL can scale automatically from small to large.
- 9:55 Document model stores the data as hierarchical key:value pairs. This is known as JSON.
- 10:25 Documents and Collections.
- Documents are JSON key:value pairs know as fields.
- maximum 1 MB of memory in size.
- Documents can't contain other documents.
- Collections are collections of documents.
- Collections can only contain strings.
- Firestore Root can only contain collections.
- Documents are JSON key:value pairs know as fields.
- 11:45 Drill down into your data format: firestore.collection(...).document(...)...
- users/user_123/workouts/workout_abc Collection/Document/Collection/Document alternating
Recommended Video
How do queries work in Cloud Firestore? | Get to Know Cloud Firestore #2 16:03 Minute Video
- Queries, How we get data out of firestore.
Highly Recommend Video
Maps, Arrays and Subcollections, Oh My! | Get to Know Cloud Firestore #4 12:49 Minute Video
- Rules
- Documents are limited to 1 MB or 20,000 fields.
- Can't retrieve less then one document.
- Security rules are based around documents.
Suggested Video
How to Structure Your Data | Get to Know Cloud Firestore #5 14:27 Minute Video
Highly Recommend Video
Security Rules! 🔑 | Get to Know Cloud Firestore #6 22:38 Minute Video
Suggested Video
How Do I Paginate My Data? | Get to Know Cloud Firestore #7 10:15 Minute Video
- How to split your data into many parts.
Suggested Video
How do Transactions Work? | Get to Know Cloud Firestore #8 16:09 Minute Video
- Atomic batch operations
# Creating a CRUD app
What is CRUD?
- C: Create Data
- R: Read Data
- U: Update Data
- D: Delete Data
Our application is going to demonstrate all of these operations. You can find the complete project code (except the file firestore.js) in github.com/mhintegrity/Lesson 26
# Commands to start Building our App.
In past lessons we have covered most of these command, but I will quickly list them in order.
Lets create our new project using the Vue CLI.
vue create vue-awards
Follow steps from Lesson 23 Vue Router to create the project
In the command line of our project we need to add firebase as a library
$ npm install -- save firebase
More details in Lesson 24 Firebase Deploy
Initiate this project, to start with we are going to only use the Hosting feature, so only choose hosting.
$ firebase init
# Create a Firestore database named awards
- In your firebase console, select/click Database
- Make sure
Cloud Firestoreis selected in the dropdown, notRealtime Database - Select/click
Add collectionto start a collection - Name the collection
awards

- Choose
Cloud Firestore - Example added document

Lets add some fields to our document.
- First field name is
titletypestring - Value is
High Kick - Next add a field
detailtypestringvalueKick over your head - Next add a field
completedtypebooleanvaluefalse - Next add a field
createdAttypetimestamp
In the next section we will update our code to add items to this collection using the app, not here in the console.
Setup a new project in the Firebase console and add the details for connecting to firebase to a new local file firebase.js, look in the settings for the api keys.

To our project we are going to add the firebase config.

- A file at the base level named
firebase.js, in lesson 24 we named itfirebaseConfig.js. - Import all functions from the firebase library using
* - We are going to export a Collection of data we create named
awards. See how we choose to call the top level collection we created:firebase.firestore().collection('awards');
# Building our views
Make a local clone of my project (in another directory) so that you can look at the code in one instance of VS Code and work on your own project in another.
git clone https://github.com/mhintegrity/Lesson26.git
First we need to load our app with a very simple main.js file.

- The hard work of loading firebase is being done in
firebase.js - If you use authentication this will need to change to follow the pattern of Lesson 25.
Our App.vue is also very simple with only links two our two views

We have placed the main details in Home.vue view
First lets see what the page will look like when running.

- The top card is always on the page.
- Below we find a list of cards displaying data from the database.
- The top card is titled New Award and has an
Addbutton for when you have finished entering a title and details. This covers C in CRUD. - The list of cards holding saved awards each have an
EditandDeletebutton. This covers U and D in CRUD. - The list of cards coming from firestore covers R in CRUD.
Lets look at the code for Home.vue

- Title at the top of the
Home.vueview. - Title of the static card at the top of the screen, which is used to add a new award.
- Input text control where the user enters a new title. We link the user input to a data variable named
newAwardTitle - Input text control where the user enters the Detail. We link the user input to a data variable named
newAwardDetail - Our add button calls a method named
addAward - We use a UL User List HTML control to list our cards. All details are contained in a component named
AwardListItem.vue - Here is the import of the AwardCard component.
- Look at CSS to see how we display our cards.
# Code to Create Data in Cloud Firestore
Clicking the Add button calls the method addAward

- Here is the JavaScript function that is called when the
Addbutton is clicked. - First we do an if check to make sure there is a title with a length of 1+, then we call the object
awardsCollectionwhich we imported usingimport { awardsCollection } from "@/firebase";. This is the collection of documents Firestore provides with the firebase library..add({})is the library function to add a new document to our collection. Using{ title: "string or string variable" }format we create a JavaScript object, which is also JSON and can be stored in our Firestore Document.- You can see more details at this google firebase page Adding Data to Cloud Firestore
.then()is called when we save successfully to Cloud Firestore..catch()is called when there is an error trying to save to Cloud Firestore.- Next we reset our variables which are linked to the screen input text boxes. We want the user to be able to enter another item.
- We call the method
refreshDatawhich performs the Read of documents from our collection in Cloud Firestore.
# Code to Read Data in Cloud Firestore
There are multiple locations where we read our collection from Cloud Firestore using the method refreshData.
The created() method is called when the app loads the Home screen, so this is the first time we call the method refreshData.

- The
refreshDatamethod represents the R in CRUD. We are going to read a collection of documents that we used to display cards on the screen.- Here is a link to the Google Firebase documentation Getting Data with Cloud Firestore
- We call the
.get()method on our firebase library.- The called to
.then()is asynchronous, which means the code makes the call to Firestore and waits in the background till it gets a response back. querySnapshotis the variable of our function that holds the returned collection of data.- We need to reset our local array that is used to display the data on our screen. The awards variable is in
data, see 7 at line 59.
- The called to
- The Javascript method
forEachwill perform a block of code for each items in our returned array (collection) of objects (documents). - This is a commented out line which will print the document id and fields in the console.
- First we create a new variable named
datato store the fields from ourdocusing the method.data() - Now we create a new object which is our award and add it to our array
this.awardsusing the JavaScript array methodpush - empty
awardsdata variable that is used to display our awards in cards. See the next code which shows how award-card is used.

- We have a list < ul > that creates an instance of the award-card component for each item in the
this.awardsarray.v-forcreates an instance of award-card for each item in the arraythis.awardsv-bind:keylinks the id field to our component instance.v-bind:awardpasses in the item from the arraythis.awardsinto the component.v-on:deleteAwardcatch's the $emit coming from the component award-card, and calls the methoddeleteAward. If you look in the component you will see that this is called when the user clicks the delete button.
- In the data section is where we define the array
this.awards - Here is where we add the objects based on the document collection returned from Firestore.
# Code to Delete Data in Cloud Firestore
When the user clicks Delete on an award card, we emit an event from the component up to App which deletes the document from Cloud Firestore.
Lets look inside the award-card component. The file is named AwardListItem.vue.

- The award object which contains our data fields and an id is passed into the component and stored in
propsasaward. - We are using a vue conditional rendering directive to switch our controls between displaying text for our title and a text input box when in edit mode. We are using the
editModeproperty of the award data variable to choose between edit and view mode. v-elsewill display the text in a label whenaward.editModeis false. Notice that the data type foreditModeis a boolean that starts out as false.- When
v-elsewe see the title label and two buttons,EditandDelete. When True we instead get the input text box and the buttonsSaveandUndo. - The delete button calls this method
deleteAwardand this method does an $emit to send a message out of award-card back up toHome.vue.

- We can see that the $emit command calls this method
deleteAwardand passing in our variableaward. - Just like our add we call a firebase method on our collection called
delete. Notice that we first call .doc and pass in our id (key) which is a call to select our document based on our key/id and then do the delete.
Read more about delete at Deleting Data from Cloud Firestore
# Code to Update Data in Cloud Firestore
In the AwardListItem.vue you can see the code that is used to edit an award, and then call updateAward in Home.vue.

- Line 54 is a function that is called when the user clicks the save button.
- Line 55, 56 set the award prop variable
titleanddetailto be the values the user has entered into the input text boxes. - Line 57 send a message up out of this component back up to Home.vue, so that it can call the update method.
- Line 58 set the component to not be in edit mode.

v-on:updateAwardwill capture the $emit from inside the component and then call the local methodupdateAwardand pass in the award object from thev-forcommand on line 35.- We start will the awardsCollection and use the
.docmethod, like we did in delete to select our document out of our collection. - Next we call the method
updatewhich accepts an object with 1 + fields. Only the fields passed in will be updated.
Here is what the screen looks like when

- Card # 1 shows a card in Edit Mode. We have the choice to undo our edit or Save it.
- Card # 2 shows a card not in Edit Mode. We can use the buttons to enter Edit mode or delete the card.
# No More Assignments
Work on your Project.
- Make sure to check-in your code to Github for your project every time you complete some work.
- After testing your code locally, deploy to Firebase.
- Ask other student in the class, and over Slack to try out what you have deployed to Firebase.