What is Firebase reference type?

Google introduced Firebase as a BaaS,Backend as a service so developers could build, host, and manage their apps with minimum code. Services like database, file storage, and user authentication make scalable app development faster and more convenient. Currently, Firebase provides a serverless development environment for all platforms, like Web, iOS, and Android. For this Answer, we’ll work with our own Firebase web app linked with a NoSQL database in Firestore.

NoSQL Firestore database
NoSQL Firestore database

The diagram is a schematic representation of a NoSQL database on the Firestore cloud. There are two collections. One is the educative_user collection, containing the name, address, and email fields, and the other is the educative_user_comments collection, which contains the user_comment and user_reference_key fields. The user_reference_key field has a reference data type and refers to the user document who commented. Let’s see what a reference data type is in the coming sections.

Reference data type

Firestore offers several data types, including the reference data type. It acts like a foreign key and can reference another data type in some other collection. A foreign key is any column in an existing collection that references another collection’s field. Although the foreign key is a term specific to relational databases, a reference data type is similar to a foreign key concept in NoSQL databases. Another option for accessing that data would be to create a nested collection—the required data to be referenced would be contained inside the root collection. However, this approach is more complex and difficult to retrieve if there is a greater nesting level. We’ll see how to access the data from the educative_user collection using user_reference_key.

Getting started with setting up the Firestore database

First, we’ll create a new project in Firebase and a database in Firestore in test mode. Before diving deep into this task, let’s first understand what Firestore is. Firestore is a NoSQL database that makes web development easier by providing high-performance and automatic scaling. Like any other NoSQL database, it contains the same features with the exception that it models relationships between objects.

We’ll need to create the educative_user and educative_user_comments collections in Firestore as shown in the diagram above.
This is how each collection should look like at the end. The following slides contain sample data, but you can populate the data as you like.

canvasAnimation-image
1 of 2

Then, initialize the Firebase web application.

After configuring the web app, create the index.html and app.js files in the public folder and paste the given code into the respective files. For this Answer, we don’t need to do this step, but we must paste our project’s configuration details and press the “Run” button for the following app to work. Otherwise, the app will not start. The lines to replace have been highlighted in the file for convenience. After doing so, run the following command:

firebase login --no-localhost
Command to log in to the Firebase account

Once the command runs in the terminal, we’ll be asked to log in to the Firebase account. Copy the link provided into any browser window to gain access to the authorization code. Paste that into the terminal window. We’ll be logged into the Firebase account if we have followed all the steps correctly. From there on, paste the following command into the terminal to launch the web app.

Run the terminal below and observe the output. If you have some experience with Firebase, you’ll notice how we have indirectly fetched the user data using the reference variable in the educative_user_comments collection.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://www.gstatic.com/firebasejs/10.7.0/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.7.0/firebase-auth-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.7.0/firebase-firestore-compat.js"></script>
    <script>
        /* Enter your configuration details here*/
        const firebaseConfig = {
            apiKey: "Your API Key",
            authDomain: "Your app domain" ,
            projectId: "Your project ID",
            storageBucket: "Your storage bucket",
            messagingSenderId: "Your messaging sender ID",
            appId: "Your App ID",
            measurementId: "Your measurement ID
        };
        firebase.initializeApp(firebaseConfig);
    </script>
    <script src="app.js" defer></script>
</head>
<body>   
</body>
</html>
Firebase web app

Code explanation

The following is a line-by-line explanation of app.js and index.html contained in the public folder of the web app.

The app.js file

Lines 1–3: We’re adding an event listener for the event when the HTML document is first loaded. Then, we initialize the app and db variables with our Firebase app and Firebase database, respectively.

Lines 5–10: These lines fetch all the documents from the educative_user_comments collection in the form of querySnapshot, which is, as the name suggests, a snapshot of the documents when this function was called. Then, we iterate over all the documents and store user_reference_key in the educative_user_reference variable. We’ll use this variable to fetch the referenced document’s data.

Lines 12–19: We’ll retrieve the referenced documents name, address, and email fields. We’ll also store the user_comment field along with it. After storing these values, we’ll display the fetched data by using the document.write JavaScript method.

Lines 21–28: This block implements the error-catching logic and renders the exception caught while fetching data from the educative_user and educative_user_comments collections to the browser.

The index.html file

Lines 7–9: To enable the Firebase functionality in the web app, we’ll import firebase-app-compat, firebase-auth-compat, and firebase-firestore-compat via their URLs. The firebase-app-compat module initializes the Firebase app instance. The firebase-auth-compat module manages user authentication, such as sign-in and sign-up, etc. The firebase-firestore-compat module is necessary for connecting to and performing CRUD operations on the Firestore cloud database.

Lines 11–19: A firebase config object is defined in this block of code, which contains configuration data, like API keys, authentication domain, app ID, etc. Firebase is initialized with the firebase.initializeApp(firebaseConfig) method.

Line 23: A script tag includes the app.js file containing the business logic for retrieving data from the database. The defer attribute ensures that the business logic inside the app.js file is executed only after document parsing.

Conclusion

The Firebase reference data type impersonates the foreign key concept in the relational databases, allowing developers to access field values present in a different collection. This is better than the nesting approach of retrieving data and greatly simplifies data organization and management for scalable app development. The example discussed above is a simple web application, but we can use Firestore’s reference data type with other platforms like iOS or Android.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved