Cloud Firestore
Firestore is a flexible database for web and mobile development. It uses data synchronization to update data on any connected device. Realtime Database is the other Firebase database, you can compare and choose the best database for your app.
How to initialize the app and set up Firestore
After creating a Firebase project, you need to integrate your React native Expo app with Firebase. Navigate to the firebase.js file and initialize an instance of Cloud Firestore:
Import the Firebase database and the methods:
You only need to import the methods you need. You should also create a Firestore database from the Firebase console: Cloud Firestore > Create database > Choose Location > Next > test mode > Create.
Rules
If you want users to read and/or write data, you should allow it from the Rules section in the Firestore Dashboard.
Firestore - How to manually create a Firestore collection and document
Open Console. Select Firestore Database from the navigation panel. You will see all the collections, documents and fields. You can click + Start Collection to create a collection. You can click + add document to create a document, you need to write a field and a value, create an identifier or generate an Auto-ID (using the Auto-ID button) and save.
Firestore - How to read data
If you want to read and use the data in the database, you can use the method getDoc():
const docRef = doc(db, "collectionname", "documentID");
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log("Document data:", docSnap.data());
} else {
console.log("No such document!");
}
Firestore - How to add data
You can use Firestore without giving users direct access, or you can allow users to store their own data. Firestore supports structured data types such as strings, numbers, and objects, but it’s not designed to store large binary files like images — for those, Firebase Storage is the appropriate tool. To create a file in Firestore, you can use the setDoc method:
await setDoc(db, "Books", "0VDv0lCXsfSW2zbNv1u0ha9")
The method creates a collection named "Books" and 0VDv0lCXsfSW2zbNv1u0ha9 is the ID of the document.
You can create a document for every user who creates an account. You need to generate an ID for their document. You can make your own method or you can use user.uid for document ID:
await createUserWithEmailAndPassword (auth, email, password).then(cred => {
return setDoc(doc(db, "Books", cred.user.uid), {email, name
})})
Firestore - How to delete a document
To delete a doc, you can use the deleteDoc method:
await deleteDoc(doc(db, "Books", "0VDv0lCXsfSW2zbNv1u0ha9"));
We used the updateDoc method to keep the existing document and add new fields or update values. If you want to completely replace the existing document, you should use the setDoc method instead. By default, setDoc() overwrites the entire document.