Saturday, June 22, 2024
Google search engine
HomeFirebaseFirebase Data Modeling Tips

Firebase Data Modeling Tips

Firestore is a flexible, scalable database for mobile, web, and server development from firebase and googles cloud. Like firebase’s real-time database, it keeps your data in-sync across client apps through real-time listeners and offers offline support for mobile and web so you can build responsive apps that work regardless of network latency or Internet connectivity. cloud Firestore also offers seamless integration with other Firebase and google cloud products, including cloud functions.

Hello friends In this blog, we will learn about Firebase data modeling tips. How to store your data in a big tree-like structure like a real-time database and how it is stored in documents and collections. so let’s get started.


Table Of Contents :

Firestore Database Model

Cloud Firestore Database Structure

Normalization & Denormalization

Security In Firestore

Conclusion



Firestore Database Model:

When we create any mobile application, it is necessary to save the input data by the user, you have to save it in the cloud. To save in the cloud, we use Google’s Firebase Firestore Database. Firestore is a kind of nozzle database that your iOS, Can be accessed directly through the native SDK for Android web apps using Cloud Firestore’s NoSql data model, storing data in all documents in which the data is mapped to the data.

Choose a Cloud Firestore Data Structure:

For any app, we have to create archives and documents in the Cloud Firestore database. If it is not in both databases, Cloud Firestore creates it. Which are used to organize the structure and formulate queries. Documents may also contain a sub collection and nested objects that may contain strings, primitive fields, or data from some lists. The document is a light-weighted record that measures all values. Which identifies each document and we can treat the document as a JSON record. For this, you have a few different options. Let’s look at the benefits of each of its options.

=> Collection:

When a user signs into the Firebase platform, each user data must be saved in the archive and we save some basic information of the user, and the user unique ID is used as the key to the document. As one can create many documents in one collection. Collections are schema-less. When a document is in the same collection, those fields can contain and store different fields and different types of data.

Let us discuss some rules of collection.

  • A collection can only contain a document and not a collection of strings, binaries, or anything else.
  • The names of his documents are unique inside the collection.
  • No document can contain any other document but it can point to sub-collections.
  • When we create the first document, a collection already exists.
  • When all documents in the collection are deleted, the collection no longer exists.
//Colection
users
//Document 1
user1
first : "Mac"
last : "Anthony"
born : 1990//Document 2
user2
first : "Abdul"
last : "Ahamed"
born : 1987

=> Document:

In the Cloud Firestore, the storage unit is a document. A document is a type of light record that contains certain fields that map to all values ​​because it can recognize it by a single name. Can nest complex objects such as arrays or maps within documents. If we have a simple and definite list of data then it is even easier to set up and streamline our data structure. The document list also increases when the document list increases, which can slow down the document recovery time.

//Document
user1
first : "Mac"
last : "Anthony"
born : 1990

=> Subcollection:

In this scenario, the correct way to store a message is to use a sub-collection. A subcollection is a collection associated with specific documents. Documents reside in collections, which are very simple containers for documents. And we can create a subcollection for each document in our collection.

Let us discuss some rules of sub collection.

  • Subcollections allow us to structure data in a hierarchy, making it easier to access data.
  • Cannot reference collection and document in the collection.
  • We can also have sub-collections in documents in sub-collections, allowing us to nest the data more.
//Collection
Rooms
//Document 1
roomAname: "my chat room"
messages
//Sub-collection 1
message1
from : "Shubham"
msg : "Hello Shubham"
//Sub-collection 2
message2
from : "Mac"
msg : "Hello Mac"//Document 2
roomB
name: "my chat room two"
messages
//Sub-collection 1
message1
from : "Sam"
msg : "Hello Sam"
//Sub-collection 2
message2
from : "Mac"
msg : "Hello Mac"

=> Nested Data Document:

We can nest complex objects such as arrays or maps using a nested data document when we have a fixed list that we want to keep in our documents. Then it becomes easy to set up and streamline the data structure It is not scalable like other options. If the data grows over time then the document grows with an increasing list.

In any chat app, we can access the 3 most recently visited chat rooms of any user in their profile as a nested list. As given in a reference below

//Document
alovelace
name :
first : "Abdul"
last : "Samad"
born : 1990
rooms :
0 : "Software Chat"
1 : "Famous Figures"
2 : "Famous SWEs"

=> Root-level Collection:

To organize individual data sets into a root level collection, we create a root level collection for our database and provide a powerful query inside each collection for good engagement with the root level collection. Cloud Firestore Root Level Allows adding more than one collection. As the database grows, acquiring naturally hierarchical data can become more complex.

As mentioned below, in a context the chat app which has a collection of users name has two different documents inside it and a collection of rooms name that makes up the root level collection, inside it is a collection of messages named Message has different documents.

//Collection
users//Document
 alovelace
first : "Abdul"
last : "Samad"
born : 1815

//Document
sride
first : "Sally"
last : "Ride"
born : 1951//Another root level collection
rooms
//Document
software
//Sub-collection
messages
//Document
message1
from : "srastogi"
content : "..."
//Document
message2
from : "srastogi"
content : "..."

With the root tag collection, in the root level collection, each tag needs to store its message ID. This flips the direction of convenience pointers.

collection("tags").whereEqualTo("messageId", messageId)

Normalization & Denormalization:

It is a technique utilized in databases that are utilized to reduce information repetition and information contradiction from a table. This is the procedure where non-repetition and dependability information is put away in the set construction. When utilizing normalization the quantity of tables increments instead of diminishes.

{
"students": {
"students1": {
"name": "john thomas"
}
},
"attendance": {
"students1": {
"attendance1": {
"total": "20",
"absents": {
"leave1": "medical emergency",
"leave2": "not verified"
}
},
"attendance2": {
"total": "18",
"absents": {
"leave1": "sports game",
"leave2": "verified"
}
}
}
}
}

Denormalization isn’t simply identified with the Cloud Firestore, however, it is additionally an innovation regularly utilized in NoSQL databases and there is the contrary interaction of normalization, where changing summed up constructions over to a solitary pattern that contains repetitive data. It is the way toward taking a standardized information base and adjusting table designs to permit controlled excess for expanded data set execution. Endeavoring to improve execution is the solitary motivation to ever denormalize an information base.

This is the way toward enhancing the presentation of a NoSQL database, called redundancy, by adding repetitive information to other various areas in the database.

=> What are the Benefits & Advantages of Normalization:

Normalization gives various advantages and benefits to a firebase. A portion of the significant advantages incorporate the following :

  • > More prominent by and large database association.
  • > Decrease of repetitive information
  • > Better execution is ensured which can be associated with the above point. As data-bases become lesser in size, the goes through the data end up being faster and more restricted in this manner improving response time and speed.
  • > Smaller tables are possible as normalized tables will be changed and will have lesser fragments that consider more data records per page.
  • > A considerably more adaptable information database plan.
  • > A superior handle on database security.

=> When and Why to Use Denormalization:

As with almost anything, you ought to be sure why you need to apply denormalization.

  • > Maintaining history: Information can change over the long run, and we need to store esteems that were substantial when a record was made. What sort of changes do we mean? All things considered, an individual’s first and last name can change; a customer likewise can change their business name or some other information. We could tackle this issue by adding a table containing the historical backdrop of these changes. Around there, a select question returning the errand and a valid customer name would turn out to be more muddled.
  • > Improving query performance: A portion of the queries may utilize different tables to get to the information that we now and again need. Think about a circumstance where we’d need to join 10 tables to return the customer’s name and the items that were offered to them.
  • > Speeding up reporting: We need certain measurements often. Making them from live information is very tedious and can influence generally framework execution. Suppose that we need to follow customer deals over specific years for a few or all customers. Creating such reports out of lived information would “dig” nearly all through the entire database and back it off a ton.
  • > Computing commonly-needed values upfront: We need to have a few qualities prepared processed so we don’t need to produce them progressively.

=> What Are the Disadvantages of Denormalization?:

Clearly, the greatest benefit of the denormalization cycle is expanded execution.

  • > space: This is normal, as we’ll have copy information.
  • > Data anomalies: We must be exceptionally mindful of the way that information currently can be changed in more than one spot. We should change each piece of copy information as needs are. We can accomplish this by utilizing triggers, exchanges, and additional methods for all tasks that should be finished together.
  • > Documentation: We should appropriately archive each denormalization decision that we have applied. On the off chance that we change the information base plan later, we’ll need to take a gander at all our exemptions and contemplate them by and by. Perhaps we needn’t bother with them any longer since we’ve settled the issue. Or then again perhaps we need to add to existing denormalization rules.
  • > Slowing other operations: We can expect that we’ll slow down information insert, modification, and deletion operations. On the off chance that these activities happen generally seldom, this could be an advantage. Fundamentally, we would isolate one lethargic select into a bigger number of more slow insert/update/delete queries.
  • > More coding: Rules 2 and 3 will require extra coding, and yet they will improve on some select inquiries a ton. In case we’re denormalizing a current information base we’ll need to alter these select inquiries to get the advantages of our work. We’ll likewise need to refresh values in recently added credits for existing records.

Security In Firestore:

Cloud Firestore security is very important for an app or web. This security rule allows us to control access to documents and collections in your database. This rule allows you to create files that can be written from all the writing to the entire database and any Matches anything until operating on a specific document.

=> How to work security rules?

The Firestore security rule checks all requests in the database. It looks for requests that meet criteria that it does not meet, such as your database. It allows the same client to write data authenticated and unauthorized. If the user writes something in the database, it rejects it.

To see how the security rules look, we will open our database in the console. As soon as it opens, a rule appears at the top, then click on it and we will allow the read and write. As shown on the screen below.

=> Security rules Types:

The Basic security rules of firestore are two reads and write. But each of its rules can be broken into subtypes.

> Read Rules Types:

  • Get (Read single document).
  • List (Read queries & collection).

> Write Rules Types:

  • Create (Write to nonexistent documents)
  • Update (Write to existing documents)
  • Delete

=> Read Rules:

The Read Rule provides both access to and listing documents in grant collections. The permission rule in this allows the user to read a document, But it does not list all the documents. But the permission list allows the user to read the entire collection and query the collection gives.

=> Write Rules:

Cloud Firestore security rules include match details. Allow write rules to create and allow grant privileges so that the user can create, update and delete something. The entire request fails if writing is not allowed.

=> Testing Rules:

Cloud Firestore offers a rules simulator that you can use to test your rules. This is a very nice feature that provides a firestore. It allows authenticated and unauthorized read, write and delete operations. When you simulate an authenticated request, you can use it to test your rule.

Default Security Rules Declaration (Default-No Read and No Write):

// DefaultFirestore Service Declaration
service cloud.firestore {
// Database Declaration
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
}
}

Security Rules Declaration (Read-Only and Write Only):

// Cloud Firestore Service Declaration
service cloud.firestore {
// Database Declaration
match /databases/{database}/documents {
match /{document=**} {
allow read: if true;
allow write: if false;
}
}
}

After that we publish it and Firestore provides a good facility to check our rules so that we can test our rules

Let’s understand these rules by breaking them line by line.

  • > service cloud. firestore — It defines the service, in which case it is the cloud.firestore.
  • > match /databases/{database}/documents —It defines the database. This database clause indicates this rule applies to all Firestore project databases.
  • > match /uploads/{document=**} —Creates a new rule block to apply to the uploaded archive and all documents contained in it.
  • > allow read: — It allows the public to read access.
  • > allow write: — allow public write access

Conclusion:

In the article, I have explained the structure of the Firebase Data Modeling Tips; you can modify this code according to your choice. This was a small introduction to Firebase Data Modeling Tips On User Interaction from my side.

I hope this blog will provide you with sufficient information in Trying up the Firebase Data Modeling Tips in your project. We showed you what the Firebase Data Modeling Tips is and how it is stored in documents and collections, So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


Feel free to connect with us
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

PDF with Flutter

Rest API in Flutter

Charts in Flutter

Spinkit In Flutter

Recent Comments