Backend Note
Published: 2021-12-23 13:46:05

Backend
CURD Operation

CRUD Operations: CRUD operation comes from computer programming that refers to four operation those are:
C for Create (POST)
R for Read(GET)
U for Update(PUT)
D for Delete.(DELETE)
Create operation: The create operation is performed when we send a post request to the server. We can send the post operating using form or core JavaScript.
Example:
Request from Client side:
fetch("URL", {
      method: "post",
      headers: {
        "content-type": "application/json",
      },
      body: JSON.stringify(),
    }).then();

Reques from Server side:
    app.post("/reviews", async (req, res) => {
      const user = req.body;
      console.log(user);
      const result = await reviewsCollection.insertOne(user);
 
      res.json(result);
    });

We have define the method and content type during post or create operation.

Read operation: The read operation is performed when we visit the website. A get request is send to server to load data in to the web site from the server
Example:
Request from Client side:
useEffect(() => {
    fetch("https://ancient-beyond-64067.herokuapp.com/reviews")
      .then((res) => res.json())
      .then((data) => setReviews(data));
  }, []);


Reques from Server side:
  app.get("/reviews", async (req, res) => {
      const cursor = reviewsCollection.find({});
      const review = await cursor.toArray();
 
      res.send(review);
    });

Update Operation: The update operation is used when we want to update or change data or information from our website. We use PUT method to update our website using form or JavaScript.

Example:
Request from Client side:
  const handleUpdateStatus = (id) => {
    const updateSataus = { status: "Approved" };
 
    fetch(`https://ancient-beyond-64067.herokuapp.com/orders/${id}`, {
      method: "PUT",
      headers: {
        "content-type": "application/json",
      },
      body: JSON.stringify(updateSataus),
    })
      .then((res) => res.json())
      .then((data) => {
        if (data.modifiedCount > 0) {
          alert("Status updated.");
          // window.location.reload();
        }
      });
  };

Request from Server side:
    app.put("/orders/:id", async (req, res) => {
      const id = req.params.id;
      const updateStatus = req.body;
      const filter = { _id: ObjectId(id) };
      const option = { upsert: true };
      const updateDoc = { $set: { status: updateStatus.status } };
      const result = await ordersCollection.updateOne(
        filter,
        updateDoc,
        option
      );
      res.json(result);
    });


Delete operation:  When we want to delete some information from our website we use Delete operation which is similar to update operation.We send a delete request from out client side to server side to delete data from our using database.

Example:
Request from Client side:
  const handleOrderDeletion = (id) => {
    const url = `https://ancient-beyond-64067.herokuapp.com/orders/${id}`;
    fetch(url, {
      method: "DELETE",
    })
      .then((res) => res.json())
      .then((data) => {
        if (data.deletedCount) {
          alert("Do you want to delete?");
          const remaining = orders.filter((order) => order?._id !== id);
          setOrders(remaining);
        }
      });
  };

Request from Server side:
 app.delete("/orders/:id", async (req, res) => {
      const id = req.params.id;
      const qurey = { _id: ObjectId(id) };
      const result = await ordersCollection.deleteOne(qurey);
      res.json(result);
    });


Relational Database(MySql)
Relational Database: A relational database management system is used to store and restore data from tables.The database consists of collections of tables that are inter related to each other.
Relational databases are based on the relational model. In the relational model each row is known as a tuple which has a unique ID called the key.
On the other hand columns are known as attributes, usually each record has a value for each attribute.


Mongoose
Mongoose: Mongoose is library of mongoDB and node Js. It is used to build relationships between data, provides schema validation and is used to translate between objects in code and the representation of those objects in MongoDB.
Currently mongoose provides eight schema type that a property is saved as when it is persisted to mongoDb .They are
String
Number
Date
Buffer
Boolean
Mixed
ObjectId
Array.
 Installation : First of all we have to install node Js and mongoDB then we have to install mongoose by commanding npm i mongoose

Connection: After installing we have to define connection. If our apps has  single database then we should use mongoose.connect . It we use more than one database we have to use mongoose.CreateConnection.

Formula: await mongoose.connect(‘mongodb://localhost/my_database’);