rd2705
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Summer B Week 5 Tinker ## Firestore Writing Data ### Creating Data Questions: * Which part are we writing data to the database? * Fill out the input, click on Add Album button and watch the data change in the database. > After filling out the input and clicking the Add Album button, a new component was added in the page, and a new document including artist and album name, was added into the collection of "album". > > We were writing data to the database using the `methods` of `creatAlbum`. Then, through `this.reset()`, we reset the form. Lastly, through `this.readAlbums()`, a new component was added to the page. * Hook up createAlbumAlternate() instead of createAlbum() * What does createAlbumAlternate() do? > This is another method that is used to add a new component in the page, which is also used to add a new document into the collection "albums". * How is it different than createAlbum()? * What do you think `let id = albumsRef.doc().id` is doing? >When we were using`createAlbum()`,the new document only included "artist" and "name". When we changed`createAlbum()`into `createAlbumAlternate()`, the automatically generated id was also in the field. Inside the method`createAlbumAlternate()`, there is `let id = albumsRef.doc().id`, which created a new document called "id". Then, inside `albumsRef.doc(id).set`, there is `id: id`, which means that the new added document will have another field "id", which refers to the "id" in the document "id". Therefore, a new document including artist, album name, and the automatically generated id, was added into the collection of "album". >Add the `let id = albumsRef.doc().id` will be more convenient when we want to access the information of id. ### Writing Data - Create * In your own project, create a new collection todos. * Database: https://console.firebase.google.com/u/0/project/city-of-data-55996/firestore/data/~2Ftodos~2Fr1ALIYgALmUt0s72vt35 * Create a reference variable to the todos collection in your Vue project. * Codepen URL: https://codepen.io/yl4516/pen/zYwWePy?editors=0010 * When a user inputs a task and then click the ADD button, that new task should be added to the todos collection. * When should the Vue app "write" data to the DB? >We did not understand what does this question want to ask actually. So from our point of view, we think that after linking the database and the application (e.g. `let db = firebase.firestore(); let todosRef = db.collection('todos');` and the configuration code), we started to "write" data to the DB. * Where we are writing the new task to? >We are writing the new tasks (new documents) to the collection "todos". * What fields will thseat new task have? > 1. The name of the task: `task` > 2. A boolean that represents the state of the task (have done or not have done): `done`(true or false). > 3. The automatically generated id of the todo ### Updating Data * Which parts are we updating data in the database? >We were updating the number of the field "positive" in the database. * Input a number and click update * What do you observe? > The typed number was updated to the number in the component. * What changes? What doesn't change? >In the database, the number of field "positive" was updated as we typed new numbers in the input box. The other fields (id, death, name, recovered) did not change. * Why some data changes and the other not? >Because in the codepen application, we created the method that could only change the number of "positive": ``` updateState(id) { statesRef.doc(id).update({ positive: this.updatePositive, }); this.updatePositive = null this.readStates(); }, ``` * Instead of `docRef.update({num:1})` what might happen if we did `docRef.set({num:1})` ? >If we did `docRef.set({num:1})` using the `set` method, all the data in the database, including the id, death, name, recovered, would be replaced by the updated data of positive number, and all the other fields except for "positive" would disappear since the whole document was replaced by the new updated positive number. --- ### Writing Data - Update Hands-On Activity: Starter code: https://codepen.io/jmk2142/pen/LYydGGd Steps: - Create a reference to the todos collection. ```javascript= let todosRef = db.collection('todos'); ``` - Create a component method in the root Vue instance that: - Has parameters that can takes the todo ID argument from the child component (See $emit) - Uses that ID to create a document reference. - Updates the todo task in the database. ```javascript= updateTodo(id, task) { todosRef.doc(id).update({ id: id, task: task }); } ``` - What is missing from this UX? Unable to mark whether a task is done or not, referring to the ```done``` field in the firestore. --- ### Deleting data - Let's click on the delete button and observe what happens in the database. - It gets deleted in the database - Which part are we deleting the data in database? - The whole document gets deleted including all fields. - How does it work? - The method called ```delete()``` - Why do we need to use $emit? - Using emit enables the method to listen for the click targeting the specific object and then to execute the method on it. - What are we passing in as the second argument? - We pass in the ```tweet.id``` as the second argument. - What happens if we remove this.readTweets(); ? - When we delete the ```this.readTweets()```in the ```deleteTweet()```, the whole app stopped popping tweets and when the whole tweets got deleted manually, it cannot restore when clicking the restore button. --- ### Create a reference to your todos collection. - When user clicks on delete button, make it so that the target document is deleted: https://codepen.io/xl3095/pen/LYymGgB - Think about how the computer knows which document the user is targeting. I am guessing the computer grab data based on the user input, such as URL from the reference object and then using the emit to target the specific one that the user is interacting with, for instance, we use id as a flag, finally implement the action based on the function tied to it. ## Firestore Reading Data ### Reading Document Data Questions: * What's the reference of the data read from the database? > ``` let db = firebase.firestore(); let stepsRef = db.collection('steps'); ``` The data referenced from the firestore database is the collection called "steps". * Explain the relationship between the data in database and data displayed in the app. > ``` stepsRef.doc('wash').get().then(doc => { console.log(doc.data()) console.log(doc) this.step = doc.data() }).catch(error => { console.log(error) }) ``` When the function readStep is mounted, Vue will look to the firestore database and find the document "wash" in the collection "steps". It will then get this data and display it, which would then allow us to view the picture of hands being washed. * What is the difference between doc and doc.data() ? * Uncomment Line 12 and 13 in codepen example and go to debug mode. >Doc refers to the document whereas doc.data() is the data within the document. So essentially Vue first has to confirm whether this "doc" actually exists, and if it does, then it will extract data from the document. Extra: * How would you change the code / data architecture if you wanted to read a collection of steps? >You would need to call on the collection called "stepsALT" instead. >This is our initial attempt: https://codepen.io/rd2705/pen/zYwRzPo >This is after seeing the solution code: https://codepen.io/rd2705/pen/wvdyqEz Hands-on Activity >Codepen: https://codepen.io/rd2705/pen/LYyQjRJ --- ### Reading Collection Data Questions: * What are the differences between reading document data and reading collection data? >Reading document data is usually only looking at data fields within the document itself. Reading collection data on the other hand allows you to pull data from all documents and fields within the collection. * From the lines where we are reading data, what are the major difference? >We need to V-bind in the html. We have created an array for steps. Most importantly, we are using querySnapshot instead of get. ``` <div class="step" v-for="step in steps">` let stepsArr = []; stepsRef.get().then(querySnapshot => { querySnapshot.forEach(doc => { console.log(doc.data()) stepsArr.push(doc.data()) }) this.steps = stepsArr }).catch(error => { console.log(error) }) ``` * What does forEach() method indicate to you? Take a guess on what does forEach() method do? >As we can see in the code above, querySnapshot allows us to use a .forEach() method. This method will help us look through each doc to find the data we need. Since we defined an array for steps, we no long need to extract individual fields using .data(), instead we can create a loop that will save us the trouble! * What are the relationships between code parts and how data "moves" from: 1) the database, 2) the component, 3) the view/display? >1) The data is first created in our firestore database. After we have created collections, documents, and fields, we can link this to the codepen by referencing the script of the data: ``` <!-- The core Firebase JS SDK is always required and must be listed first --> <script src="https://www.gstatic.com/firebasejs/7.10.0/firebase-app.js"></script> <!-- Add SDKs for Firebase Firestore--> <script src="https://www.gstatic.com/firebasejs/7.10.0/firebase-firestore.js"></script> <script> // Your web app's Firebase configuration const firebaseConfig = { apiKey: "AIzaSyDJHhNR8H7cUxRoW2udifdtRddUqWn2Rw4", authDomain: "mstu5013-classwork.firebaseapp.com", databaseURL: "https://mstu5013-classwork.firebaseio.com", projectId: "mstu5013-classwork", storageBucket: "mstu5013-classwork.appspot.com", messagingSenderId: "101731794475", appId: "1:101731794475:web:b2df979e7d2b255ef5346e", measurementId: "G-EYWKRQ4W56" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); </script> ``` >Then, in Vue.js, we need to call on the database and create a name for our reference: ``` let db = firebase.firestore(); let stepsRef = db.collection('stepsALT'); ``` >2) We would need to create a component that uses the data from the database: ``` let app = new Vue({ el: "#app", data: { steps: [] }, methods: { readSteps() { let stepsArr = []; stepsRef.get().then(querySnapshot => { // console.log(querySnapshot) querySnapshot.forEach(doc => { console.log(doc.data()) stepsArr.push(doc.data()) }) this.steps = stepsArr }).catch(error => { console.log(error) }) } }, mounted() { this.readSteps() } }); ``` >This is usually done first by inputting the reference array in data. And then in methods, we would need to call on the firestore data. Depending on using collections or documents, we would determine whether to use 'get' or querySnapshot. Once the data is mounted, we are ready to display it. >3. To display the data, we need to add some references to our html code: ``` <div id="app"> <h2>Take Steps to Protect Yourself and Others</h2> <div class="step" v-for="step in steps"> <img :src="step.photoURL"> <p>{{ step.name }}</p> </div> </div> ``` In addition to our typical Vue code beginning, we need to reference the data in firestore using our reference name under data in Vue.js inside the curly braces. If we are referencing a collection and there is an array, then we would need to create v-binds (for images in this case) and a v-for to call on several documents at the same time. Hands-on Activity * Codepen: https://codepen.io/rd2705/pen/jOmZGMz

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully