In this tutorial, we will explore how to perform CRUD operations - Create, Read, Update, and Delete, with Firebase Realtime Database. The Firebase Realtime Database is a cloud-hosted NoSQL database that lets you store and sync data between your users in realtime.
You will learn how to:
- Set up a Firebase project and integrate it with your application.
- Create, Read, Update, and Delete data from a Firebase Realtime Database.
Prerequisites:
- Basic knowledge of JavaScript.
- Node.js and NPM installed on your computer.
- A Google Account to access the Firebase console.
npm init -y
in your terminal.npm install firebase
.index.js
and include the Firebase configuration object which you can find in your Firebase project settings.const firebase = require('firebase');
const config = {
// Your Firebase configuration object
};
firebase.initializeApp(config);
const db = firebase.database();
To write data to Firebase, we use the set()
function:
const userRef = db.ref('users/user1');
userRef.set({
name: 'John Doe',
email: 'john.doe@example.com'
}).then(() => console.log('Data written successfully'));
In this example, we're creating a new user with the user ID of user1
, and setting their name and email.
To read data from the database, we use the once()
function:
const userRef = db.ref('users/user1');
userRef.once('value', snapshot => {
console.log(snapshot.val());
});
Here, we're reading the user data we just created. once()
triggers a one-time read from the database, and snapshot.val()
returns the data.
To update data, we use the update()
function:
const userRef = db.ref('users/user1');
userRef.update({
email: 'new.email@example.com'
}).then(() => console.log('Data updated successfully'));
In this example, we're updating the email of user1
.
To delete data, we use the remove()
function:
const userRef = db.ref('users/user1');
userRef.remove()
.then(() => console.log('Data removed successfully'));
Here, we're deleting the user user1
from our database.
In this tutorial, we learned how to perform CRUD operations with Firebase Realtime Database. We learned how to write, read, update, and delete data from our database.
Next, you might want to learn how to listen for data changes in realtime, handle user authentication with Firebase, or structure your data for scalability.
Tip: You can use db.ref('users').push().key
to generate a unique ID.
Exercise: Read the data of the user you just created and log it to the console.
'users/user1'
with the path to your new user.Tip: Make sure your database rules allow read access to the data you're trying to read.
Exercise: Update the email of the user you just created.
Solution: Similar to the 'Update Data' example above, but replace 'users/user1'
with the path to your new user.
Exercise: Delete the user you just created.
'users/user1'
with the path to your new user.