Perform CRUD Operations
In this tutorial, we will explore how to perform CRUD (Create, Read, Update, Delete) operations using MagicJS, enabling seamless interaction with a backend database.
Last updated
In this tutorial, we will explore how to perform CRUD (Create, Read, Update, Delete) operations using MagicJS, enabling seamless interaction with a backend database.
Last updated
Create a React component file named db-test
with the path /db
.
Add buttons for CRUD operations: Add Product, Get Product, Update Product and Delete Product.
Create a backend file named add
within the main-features
folder.
Import the data
function from magicjs.dev/backend
.
Use data()
to connect to MongoDB and specify the collection name as 'products
'.
Utilize MongoDB's functions to add products, such as insertOne()
.
Refer the snippet below.
Import addServer
into the frontend component.
Call addServer
in the onClick event of the Add Product button to trigger an alert indicating successful addition.
Refer the snippet below.
Create a backend file named list
.
Import data
and fetch all products using find().toArray()
.
Return the list of products.
Refer the snippet below.
Import listServer
into the frontend component.
Call listServer
in the onClick event of the Get Product button, displaying an alert with a comma-separated list of product names upon clicking.
Refer the snippet below.
Create a backend file named update
.
Import data
and utilize updateOne()
to modify product details.
Pass both the old and new names of the product to be updated.
Refer the snippet below.
Import updateServer
into the frontend component.
Call updateServer
in the onClick event of the Update Product button, triggering an alert upon successful update.
Refer the snippet below.
Create a backend file named delete
.
Import data
and use deleteOne()
to remove a product based on specified criteria.
Refer the snippet below.
Import deleteServer
into the frontend component.
Call updateServer
in the onClick event of the Delete Product button, triggering an alert upon successful deletion.
Refer the snippet below.
Click the Connect to Database button in the bottom section.
Click the Launch MongoDB Express button.
Login with the provided credentials.
Once logged in, you will be able to view and interact with the database.
🎉 Congratulations! You have successfully implemented CRUD operations using MagicJS, enabling seamless interaction with a backend database.
By mastering these techniques, you can create dynamic and responsive applications with robust data management capabilities. Experiment with different functionalities to enhance your web development projects further.