# Perform CRUD Operations

{% 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="/files/WqBbQWyf7JGCocmQcHis" 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="/files/iK02olPvo6xLFJajMxgB" 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="/files/tkaluhhaWQdGqjzrGeQU" 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="/files/9tHivI7yyTJFqxg8jjPQ" 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="/files/8wX4oWwRScoNGFuvCkxB" 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="/files/v85ptJ58nZA1MxQuMVmb" alt=""><figcaption><p>Connect to MongoDB</p></figcaption></figure>

<figure><img src="/files/h8tVdFehFegAOndTA0HJ" 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.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://skyslit.gitbook.io/magicjs/basic-guide/perform-crud-operations.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
