DEV Community

Building an App with a Cloud NoSQL Database (Avoiding DynamoDB or Cosmos DB)

Cloud-based NoSQL databases have become increasingly popular due to their scalability, flexibility, and ability to handle unstructured data. However, some developers may need to avoid commonly used services like AWS DynamoDB or Azure Cosmos DB, either for cost, compatibility, or preference reasons. In this article, we'll explore how to build an app using an alternative cloud NoSQL database, Firebase Firestore, and demonstrate its implementation with sample code.

Why Use a Cloud NoSQL Database?
NoSQL databases are ideal for:

  • Scalability: Easily handle large volumes of data across distributed systems.
  • Flexibility: Store data in various formats (JSON, key-value, document, etc.).
  • Real-Time Sync: Many NoSQL databases, like Firestore, provide real-time capabilities.
  • Ease of Use: Simplified data modeling compared to relational databases. In this article, we’ll use Firebase Firestore, a document-based database that offers real-time synchronization, scalability, and serverless management, making it an excellent alternative to DynamoDB or Cosmos DB.

Technologies We'll Use

  • Database: Firebase Firestore
  • Frontend: React.js
  • Backend: Node.js (optional)
  • Cloud Environment: Firebase Hosting (optional)

Setting Up Firebase Firestore
Step 1: Create a Firebase Project

  1. Visit Firebase Console.
  2. Create a new project and enable Firestore under the "Build" section.

Step 2: Install Firebase SDK
Add Firebase to your project by installing the Firebase SDK in your React app:
npm install firebase

Step 3: Configure Firebase in Your App
Create a firebaseConfig.js file to initialize Firebase:
`// firebaseConfig.js
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';

const firebaseConfig = {
apiKey: "your-api-key",
authDomain: "your-app.firebaseapp.com",
projectId: "your-project-id",
storageBucket: "your-project-id.appspot.com",
messagingSenderId: "your-sender-id",
appId: "your-app-id"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

export default db;`

Building the App
Project Structure

cloud-no-sql-app/
│-- src/
│   ├── components/
│   │   ├── AddItem.js
│   │   ├── ItemList.js
│   └── firebaseConfig.js
│-- App.js
└── package.json

Enter fullscreen mode Exit fullscreen mode

Backend: Firestore CRUD Operations
Adding Data
To add a document to a Firestore collection:

import { collection, addDoc } from 'firebase/firestore';
import db from './firebaseConfig';

const addItem = async (item) => {
    try {
        const docRef = await addDoc(collection(db, 'items'), item);
        console.log('Document written with ID:', docRef.id);
    } catch (e) {
        console.error('Error adding document:', e);
    }
};

Enter fullscreen mode Exit fullscreen mode

Reading Data
To fetch all documents from a Firestore collection:

import { collection, getDocs } from 'firebase/firestore';

const fetchItems = async () => {
    const querySnapshot = await getDocs(collection(db, 'items'));
    querySnapshot.forEach((doc) => {
        console.log(`${doc.id} =>`, doc.data());
    });
};

Enter fullscreen mode Exit fullscreen mode

Deleting Data
To delete a document:

import { doc, deleteDoc } from 'firebase/firestore';

const deleteItem = async (id) => {
    await deleteDoc(doc(db, 'items', id));
    console.log('Document deleted with ID:', id);
};

Enter fullscreen mode Exit fullscreen mode

Frontend: React Components
AddItem Component

import React, { useState } from 'react';
import { addItem } from './firebaseConfig';

const AddItem = () => {
    const [item, setItem] = useState('');

    const handleSubmit = async (e) => {
        e.preventDefault();
        await addItem({ name: item });
        setItem('');
    };

    return (
        <form onSubmit={handleSubmit}>
            <input
                type="text"
                value={item}
                onChange={(e) => setItem(e.target.value)}
                placeholder="Enter item name"
            />
            <button type="submit">Add Item</button>
        </form>
    );
};

export default AddItem;

Enter fullscreen mode Exit fullscreen mode

ItemList Component

import React, { useState, useEffect } from 'react';
import { fetchItems } from './firebaseConfig';

const ItemList = () => {
    const [items, setItems] = useState([]);

    useEffect(() => {
        const getItems = async () => {
            const data = await fetchItems();
            setItems(data);
        };
        getItems();
    }, []);

    return (
        <ul>
            {items.map((item) => (
                <li key={item.id}>{item.name}</li>
            ))}
        </ul>
    );
};

export default ItemList;

Enter fullscreen mode Exit fullscreen mode

Running the App

  1. Start your development server:
npm start

Enter fullscreen mode Exit fullscreen mode
  1. Add items and view them in real time via the Firestore Console or your app.

GitHub Repository
You can find the complete source code for this project on GitHub:
GitHub Repository: https://github.com/Angelica-R/cloud-no-sql-app.git

Conclusion
Using Firebase Firestore, you can easily build scalable applications without relying on SQL Server, DynamoDB, or Cosmos DB. Firestore's real-time synchronization and simplicity make it a strong choice for projects that require cloud-hosted NoSQL databases. By following this tutorial, you’ve learned how to set up Firestore, perform CRUD operations, and integrate it into a React app.

Top comments (0)