0Pricing
Firebase Auth & Realtime Database Apps · درس

قراءة البيانات وكتابتها

تعلّم تنفيذ عمليات الإنشاء والقراءة والتحديث والحذف (CRUD) الأساسية على Realtime Database

قراءة البيانات وكتابتها درس مجاني في Firebase Auth & Realtime Database Apps على CoddyKit. هذا هو الدرس 2 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Firebase Auth & Realtime Database Apps، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Firebase Auth & Realtime Database Apps 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

CRUD: Create, Read, Update, Delete

Welcome to working with Firebase Realtime Database! Today, we'll master the fundamental operations known as CRUD:

  • Create: Adding new data
  • Read: Retrieving existing data
  • Update: Modifying existing data
  • Delete: Removing data

These operations are the building blocks for almost any application that stores information.

Getting a Database Reference

Before we can perform any CRUD operations, we need to get a reference to our Realtime Database. This reference points to a specific location in your database's JSON tree.

First, ensure Firebase is initialized in your app. Then, you can get the database instance and a reference to a specific path.

import { initializeApp } from "firebase/app";
import { getDatabase, ref } from "firebase/database";

// Your web app's Firebase configuration
const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
  databaseURL: "https://YOUR_PROJECT_ID.firebaseio.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);

// Get a reference to the database service
const db = getDatabase(app);

// Get a reference to the 'users' path
const usersRef = ref(db, 'users');
console.log("Database reference obtained.");

Creating Data with set()

The set() method is used to write or overwrite data at a specific database reference. It's like assigning a value to a key in a JSON object.

If data already exists at the specified path, set() will completely replace it with the new data you provide.

Creating Data with push()

When you're working with lists of data, like a chat feed or a list of blog posts, you often want to add new items without overwriting existing ones. The push() method is perfect for this.

push() generates a unique, timestamp-based key for each new child. This ensures that new data is always added as a distinct entry.

Code: Writing Data (set & push)

Let's see set() and push() in action. We'll create a single user with set() and then add multiple messages using push().

import { initializeApp } from "firebase/app";
import { getDatabase, ref, set, push } from "firebase/database";

// Assume Firebase is initialized and 'db' is available
const firebaseConfig = { databaseURL: "https://YOUR_PROJECT_ID.firebaseio.com" }; // Simplified for demo
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);

// 1. Using set() to create/overwrite a user
const userRef = ref(db, 'users/user123');
set(userRef, {
  name: "Alice",
  email: "alice@example.com"
}).then(() => {
  console.log("User 'Alice' set.");
}).catch(error => {
  console.error("Error setting user: ", error);
});

// 2. Using push() to add messages to a list
const messagesRef = ref(db, 'messages');
push(messagesRef, {
  text: "Hello Firebase!",
  timestamp: Date.now()
}).then(() => {
  console.log("Message 1 pushed.");
});

push(messagesRef, {
  text: "This is a second message.",
  timestamp: Date.now()
}).then(() => {
  console.log("Message 2 pushed.");
});

Reading Data with onValue()

To retrieve data, Firebase Realtime Database offers powerful real-time listeners. The onValue() method is used to listen for changes at a database reference.

Whenever data at that location (or any child locations) changes, the provided callback function will be triggered with a DataSnapshot containing the new data.

Code: Reading Data (onValue)

This example demonstrates how to use onValue() to listen for and log all messages in our 'messages' path. It will update in real-time if new messages are added!

import { initializeApp } from "firebase/app";
import { getDatabase, ref, onValue } from "firebase/database";

// Assume Firebase is initialized and 'db' is available
const firebaseConfig = { databaseURL: "https://YOUR_PROJECT_ID.firebaseio.com" }; // Simplified
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);

const messagesRef = ref(db, 'messages');

// Listen for data changes
onValue(messagesRef, (snapshot) => {
  const data = snapshot.val();
  if (data) {
    console.log("--- Current Messages ---");
    // Iterate over the messages if they are an object
    Object.keys(data).forEach(key => {
      console.log(`ID: ${key}, Text: ${data[key].text}`);
    });
    console.log("------------------------");
  } else {
    console.log("No messages found.");
  }
}, (error) => {
  console.error("Error reading messages: ", error);
});

console.log("Listening for messages...");

Updating Data with update()

Sometimes you only need to modify specific fields of an existing record without overwriting the entire node. That's where the update() method comes in.

update() takes an object containing key-value pairs. It merges these new values into the existing data at the specified path, leaving other fields untouched.

import { initializeApp } from "firebase/app";
import { getDatabase, ref, update } from "firebase/database";

// Assume Firebase is initialized and 'db' is available
const firebaseConfig = { databaseURL: "https://YOUR_PROJECT_ID.firebaseio.com" }; // Simplified
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);

// Update specific fields of a user
const userRef = ref(db, 'users/user123');
update(userRef, {
  email: "alice.smith@example.com",
  age: 30
}).then(() => {
  console.log("User 'Alice' updated.");
}).catch(error => {
  console.error("Error updating user: ", error);
});

Deleting Data with remove()

When data is no longer needed, you can remove it using the remove() method. This method deletes the data at the specified database reference, including all its children.

Be careful with remove()! Once data is deleted, it's gone forever from your database.

import { initializeApp } from "firebase/app";
import { getDatabase, ref, remove } from "firebase/database";

// Assume Firebase is initialized and 'db' is available
const firebaseConfig = { databaseURL: "https://YOUR_PROJECT_ID.firebaseio.com" }; // Simplified
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);

// Delete a specific user
const userToDeleteRef = ref(db, 'users/user123');
remove(userToDeleteRef).then(() => {
  console.log("User 'user123' deleted.");
}).catch(error => {
  console.error("Error deleting user: ", error);
});

// To delete a specific message (e.g., if you know its ID)
// const specificMessageRef = ref(db, 'messages/-M_someUniqueId');
// remove(specificMessageRef);

Quick Check: CRUD Operations

Which Firebase Realtime Database method should you use to add a new item to a list without overwriting existing data, ensuring each new item gets a unique key?

Recap & Next Steps

Great job! You've learned the core CRUD operations for Firebase Realtime Database:

  • Create: Use set() to write/overwrite data, or push() for unique keys in lists.
  • Read: Use onValue() to listen for real-time data changes.
  • Update: Use update() to modify specific fields without replacing the entire node.
  • Delete: Use remove() to delete data at a specific reference.

Understanding these operations is crucial for building dynamic, data-driven applications. Next, we'll explore best practices for structuring your data to optimize performance and scalability!

الأسئلة الشائعة

هل درس «قراءة البيانات وكتابتها» مجاني؟

نعم — نص درس «قراءة البيانات وكتابتها» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Firebase Auth & Realtime Database Apps، انتقل إلى CoddyKit PRO. تتضمن دورة Firebase Auth & Realtime Database Apps 4 دروس في المجموع.

ماذا ستتعلم في «قراءة البيانات وكتابتها»؟

تعلّم تنفيذ عمليات الإنشاء والقراءة والتحديث والحذف (CRUD) الأساسية على Realtime Database تتمرن على Firebase Auth & Realtime Database Apps مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Firebase Auth & Realtime Database Apps؟

لا تُشترط خبرة سابقة. Firebase Auth & Realtime Database Apps على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 2 من أصل 4.

كم من الوقت يستغرق درس «قراءة البيانات وكتابتها»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Firebase Auth & Realtime Database Apps هذا؟

نعم. كل درس في Firebase Auth & Realtime Database Apps يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. أساسيات Realtime Database
  2. قراءة البيانات وكتابتها
  3. هيكلة بياناتك
  4. الاستماع إلى التغييرات الفورية
← العودة إلى Firebase Auth & Realtime Database Apps