Create, Read, Update, Delete data by using Node.js - Mongoose
Tags: node, mongodb, crud, mongoose
Published: 2022-04-06 23:21:04

In this article, we have a store and we are going to save its stuff in the database for the use of the **CRUD** process.
if you need the source of my code you feel free to check my **_GitHub_** link [here](https://github.com/sasan-dehghanian) 

At first, we should install the mongoose package in the application with the terminal by using the following code :

**`npm install mongoose`**

Then, we run the server through express and create our model’s file and write the commands as below:

```javascript
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const productSchema = new Schema({
  title: {
    type: String,
    required: true
  },
  price: {
    type: Number,
    required: true
  },
  description: {
    type: String,
    required: true
  },
  imageUrl: {
    type: String,
    required: true
  }
});

module.exports = mongoose.model('Product',productSchema);

```
After that, in the controller’s file, we write my CRUD’s code stage by stage. It is worth mentioning that by using **template-engine EJS** we find access to the front-end section and exchange the required data for importing and reading through URL. 
At the beginning of the controller file, we require our pre-defined model in the **Product** variable to be able to communicate with the database in all the functions. It should be noted that capitalization in variables that contain models is common among web developers however it is not compulsory.

##**Create:** 
for data saving in the database, first, we should save the received data in the variable. Next, we define a variable named productData, and by using the **`new`** command we import our received data into our model (Product). After that, we use **`Async/Await`** promise to write a saving command to store our data.

```javascript
exports.postAddProduct = async (req, res, next) => {
  const title = req.body.title;
  const imageUrl = req.body.imageUrl;
  const price = req.body.price;
  const description = req.body.description;
  const productData = new Product({
    title: title,
    price: price,
    description: description,
    imageUrl: imageUrl
  });
  try {
    const result = await productData.save();
    res.redirect("/admin/products");
  } catch (err){
    console.log(err);
  }
};
```
When we are saving data in the model, the first variables are our field names which we create in our model in the first steps, and the second variables are our received data if both variables have the same name, we can write the variable’s name just one time as below:

```javascript
const productData = new Product({
    title,
    price,
    description,
    imageUrl
  });
```

## **Read:**
For fetching our data from the database we could use the **`find`** command on the model’s variable as below:

```javascript
exports.getAdminProducts = async (req, res, next) => {

  try {
    const products = await Product.find()
    
    res.render("admin/products", {
      pageTitle: "Admin Products",
      products: products,
      path: "/admin/products",
    });
  } catch (err) {
    console.log(err);
  }
};
```

For reading a specialized field from our database we could use the **`select()`** command to fetch our data. As in the example below, we have read only the name and price of each product:

```javascript
Const products = await Product.find.select(‘title price’)
```


## **Update:**
 
To update, first, like creating, we put our data in the variables, then using the ID we received, which indicates which product we want to update, we search in the database and perform the update operation. For this step, we use the **`findByIdAndUpdate()`** command, in which at the beginning we input my received ID next we write the whole data to update.

```javascript
exports.postEditProduct = async (req, res, next) => {
  const productId = req.body.productId;
  const updatedTitle = req.body.title;
  const updatedPrice = req.body.price;
  const updatedImageUrl = req.body.imageUrl;
  const updatedDesc = req.body.description;

  try {
    await Product.findByIdAndUpdate(productId, {
      title: updatedTitle,
      price: updatedPrice,
      description: updatedDesc,
      imageUrl: updatedImageUrl
    });
    res.redirect("/admin/products");
  } catch (err) {
    console.log(err)
  }
};
```

## **Delete:** 

In this section, first we put my received Id in the **productId** variable, then with the **`findByIdAnRemove()`** command we find and remove the product.

```javascript
exports.postDeleteProduct = async (req, res, next) => {
  const productId = req.body.productId;
  try {
    await Product.findByIdAndRemove(productId);
    res.redirect("/admin/products");
  } catch (err) {
    console.log(err)
  }  
};
```

In this article, we tried to describe the **_CRUD_** operation with **_NodeJS_** and **_MongoDB_** without going into the details, such as the validation of entry data. 
I hope this article was helpful for you, and in case you have any questions, do not hesitate and contact me.

Sincerely,
Sasan Dehghanian