> For the complete documentation index, see [llms.txt](https://skyslit.gitbook.io/magicjs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://skyslit.gitbook.io/magicjs/basic-guide/perform-crud-operations.md).

# 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.

{% embed url="<https://www.youtube.com/watch?v=rtndX85uMjE>" %}
Perform CRUD Operations
{% endembed %}

## Setup

1. Create a React component file named `db-test` with the path `/db`.
2. Add buttons for CRUD operations: Add Product, Get Product, Update Product and Delete Product.

{% code title="db-test.tsx" %}

```tsx
import React from "react"
import { Button } from "antd"

export default function Component(props: any) {
    return (
        <div>
            <Button>Add Product</Button>
            <Button>Get Product</Button>
            <Button>Update Product</Button>
            <Button>Delete Product</Button>
        </div>
    )
}
```

{% endcode %}

<details>

<summary>Expand for Tailwind styled code.</summary>

{% code title="db-test.tsx" lineNumbers="true" %}

```typescript
import React from "react"
import { Button } from "antd"

export default function Component(props: any) {
  return (
    <div className="h-screen flex items-center justify-center">
      <Button className="text-xl w-60 h-14">
        Add Product
      </Button>
      <Button className="text-xl w-60 h-14">
        Get Product
      </Button>
      <Button className="text-xl w-60 h-14">
        Update Product
      </Button>
      <Button className="text-xl w-60 h-14">
        Delete Product
      </Button>
    </div>
  )
}
```

{% endcode %}

</details>

<figure><img src="https://629398272-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrhfVeNvXQhNiRfJxJ9pq%2Fuploads%2FA5UrLZd8X4fXGMqXo4Uq%2FCRUD%201.png?alt=media&amp;token=2b7d5253-5f66-459d-913e-1118f4f31a75" alt=""><figcaption><p>Tailwind styled output</p></figcaption></figure>

## Create

### Backend Configuration

1. Create a backend file named `add` within the `main-features` folder.
2. Import the `data` function from `magicjs.dev/backend`.
3. Use `data()` to connect to MongoDB and specify the collection name as '`products`'.
4. Utilize MongoDB's functions to add products, such as `insertOne()`.

> Refer the snippet below.

{% code title="add.server.tsx" %}

```tsx
import { createBackendFunction, data } from "@magicjs.dev/backend"

export default createBackendFunction(async function (name: string) {

    await data('products').insertOne({
        name
    })

    return "Message from server"
})
```

{% endcode %}

### Frontend Configuration

1. Import `addServer` into the frontend component.
2. Call `addServer` in the onClick event of the Add Product button to trigger an alert indicating successful addition.

> Refer the snippet below.

{% code title="db-test.tsx" %}

```tsx
import React from "react"
import { Button } from "antd"
import addServer from "./add.server"

export default function Component(props: any) {
    return (
        <div>
            <Button onClick={() => addServer('Rubiks Cube').then(() => alert('Added'))}>
                Add Product
            </Button>
            <Button>Get Product</Button>
            <Button>Update Product</Button>
            <Button>Delete Product</Button>
        </div>
    )
}
```

{% endcode %}

<figure><img src="https://629398272-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrhfVeNvXQhNiRfJxJ9pq%2Fuploads%2FWXeM6OVU8GXxogu4Iy4G%2FCRUD%202.png?alt=media&amp;token=b4504a64-65dc-4a84-9ec3-b7c846f05d70" alt=""><figcaption><p>Create</p></figcaption></figure>

## Read

### Backend Configuration

1. Create a backend file named `list`.
2. Import `data` and fetch all products using `find().toArray()`.
3. Return the list of products.

> Refer the snippet below.

{% code title="list.server.tsx" %}

```tsx
import { createBackendFunction, data } from "@magicjs.dev/backend"

export default createBackendFunction(async function () {

  const allProducts = await data('products').find().toArray()

  return allProducts
})
```

{% endcode %}

### Frontend Configuration

1. Import `listServer` into the frontend component.
2. 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.

```tsx
<Button
    onClick={() => listServer()
        .then((allProducts) => alert(allProducts.map((p) => p.name)
            .join(', ')))}>
    Get Product
</Button>
```

<figure><img src="https://629398272-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrhfVeNvXQhNiRfJxJ9pq%2Fuploads%2FMTPpu4beqwQI4YhlMLdg%2FCRUD%203.png?alt=media&amp;token=728040ad-2aaa-442b-b16f-cf3edbd95179" alt=""><figcaption><p>Read</p></figcaption></figure>

## Update

### Backend Configuration

1. Create a backend file named `update`.
2. Import `data` and utilize `updateOne()` to modify product details.
3. Pass both the old and new names of the product to be updated.

> Refer the snippet below.

{% code title="udpate.server.tsx" %}

```tsx
import { createBackendFunction, data } from "@magicjs.dev/backend"

export default createBackendFunction(async function (name: string, newName: string,) {
    data("products").updateOne({ name },
        {
            $set: {
                name: newName,
            },
        },
    )

    return "Message from server"
})
```

{% endcode %}

### Frontend

1. Import `updateServer` into the frontend component.
2. Call `updateServer` in the onClick event of the Update Product button, triggering an alert upon successful update.

> Refer the snippet below.

```tsx
<Button
    onClick={() => updateServer('Rubiks Cube', 'Water Bottle')
        .then(() => alert("Updated"))}>
    Update Product
</Button>
```

<figure><img src="https://629398272-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrhfVeNvXQhNiRfJxJ9pq%2Fuploads%2F7xrQAHyKUkWDgfQYgEqd%2FCRUD%204.png?alt=media&amp;token=9ed41072-5030-48c6-93eb-6661dc5d9db0" alt=""><figcaption><p>Update</p></figcaption></figure>

## Delete

### Backend Configuration

1. Create a backend file named `delete`.
2. Import `data` and use `deleteOne()` to remove a product based on specified criteria.

> Refer the snippet below.

```tsx
import { createBackendFunction, data } from "@magicjs.dev/backend"

export default createBackendFunction(async function (name: string) {
    await data('products').deleteOne({ name })

    return "Message from server"
})
```

### Frontend Configuration

1. Import `deleteServer` into the frontend component.
2. Call `updateServer` in the onClick event of the Delete Product button, triggering an alert upon successful deletion.

> Refer the snippet below.

```tsx
<Button
    onClick={() => deleteServer('Water Bottle')
        .then(() => alert('Deleted'))}>
    Delete Product
</Button>
```

<figure><img src="https://629398272-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrhfVeNvXQhNiRfJxJ9pq%2Fuploads%2FNmAZgaqoDIG2VSzl5KRD%2FCRUD%205.png?alt=media&amp;token=cf3bbc31-6618-4176-941d-45358a209745" alt=""><figcaption><p>Delete</p></figcaption></figure>

## Access MongoDB database

1. Click the **Connect to Database** button in the bottom section.
2. Click the **Launch MongoDB Express** button.
3. Login with the provided credentials.

<figure><img src="https://629398272-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrhfVeNvXQhNiRfJxJ9pq%2Fuploads%2FEWywdWzBNTCRlzB2nNJx%2FScreenshot%202024-02-07%20at%201.39.16%20PM.jpg?alt=media&amp;token=24b5c6b0-492e-4eb2-8e4d-775c27c04795" alt=""><figcaption><p>Connect to MongoDB</p></figcaption></figure>

<figure><img src="https://629398272-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrhfVeNvXQhNiRfJxJ9pq%2Fuploads%2FjC8CAW8SmDpTuIR72V38%2FMongoDB.png?alt=media&amp;token=0dd13f89-8a71-4fc9-9392-3129427d02d6" alt=""><figcaption><p>MongoDB Express - Web</p></figcaption></figure>

> Once logged in, you will be able to view and interact with the database.

:tada: 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.
