NodeJS CRUD API with MongoDB
Tags: node, mongodb, mongoose, restapi
Published: 2020-10-04 06:13:51

If you've been in the web development world, the chances are: you already have heard about NodeJS and MongoDB. The NodeJS official page defines it as **Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.** Also, MongoDB is one of the most popular NoSQL database. In this article we're going to perform CRUD operation on MongoDB using NodeJS along with tools express & mongoose.

> Prerequisite

If you're to get started i assume you already have set-up a MongoDB cluster and have the connection URI. If not so then you can find how to set it up in my  [previous article](https://blogs.rajankalwar.com.np/getting-started-with-mongodb) , it will guide you step-by-step on setting up Free MongoDB cluster. I also assume you've some working knowledge with NodeJS and express.

> Setting Up

In order to get started, first thing we'll do is create the file structure. I suggest you to create a root folder and then inside the root folder, create the following sub-folders:

![mongonode.JPG](https://cdn.hashnode.com/res/hashnode/image/upload/v1601790296782/Z644Dswdl.jpeg)

> Installing Dependencies

Now, to get started, we first need to create a file *server.js* and then install few required dependencies. In order to do so, 


```
npm init -y


touch server.js
touch .env
mkdir controllers
mkdir models
mkdir routes

npm install express mongoose dotenv cors body-parser

``` 

This will complete our folder structure and dependencies installation. Now the next step will be to get our mongoDB connection URI and place it in a *.env* file. In order to do so, open your .env file and edit it as:


```
DB = "YOUR_CONNECTION_STRING_HERE"

``` 

> Setting up Server and Routes

Now, let's edit our *server.js* file in order to set up the routes. Copy and paste the following code in your server.js file:

```
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");

require("dotenv").config();

const app = express();

const routes = require("./app/routes");

var corsOptions = {
  origin: "http://localhost:8081",
};

app.use(cors(corsOptions));

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: true }));

let DB = process.env.DB;

mongoose
  .connect(DB, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log("mongoDB connected Successfully"))
  .catch((err) => console.log(err));

app.use("/api/notes", routes);

const PORT = process.env.PORT || 8080;

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

```

So basically what we're doing here is
- Bringing in required dependencies
- Bringing in *Routes*(which we haven't created yet but will shortly) 
- Connecting to mongoDB

> Creating Models

Since we're using MongoDB and Mongoose, we must have to have models. In this app, we'll have only one model **NotesModel** which will contain the fields for our notes.
So let's create a file *NotesModel.js* file inside **models** folder and paste the following code:

```
const mongoose = require("mongoose");

const NotesSchema = new mongoose.Schema(
  {
    title: String,
    description: String,
  },
  { timestamps: true }
);

const Note = mongoose.model("Note", NotesSchema);
module.exports = Note;

```

So essentially, we just have 2 fields *title* and *description* of string types to keep things simple. Also the *timestamps* has been set to true which will record the creation and modification date.

> Creating Router and Controller

Now, the *server.js* is all setup, we can start setting up our controller and Router.
Inside controller folder, create a file *index.js* and paste the following code:

```
const NotesModel = require("../models/NotesModel");

exports.findAll = async (req, res) => {
  try {
    const notes = await NotesModel.find({});
    res.send(notes);
  } catch (error) {
    res.status(500).send({
      message: error.message || "Some error occured while retrieving Notes",
    });
  }
};

exports.create = async (req, res) => {
  const Note = req.body;

  try {
    let NoteDoc = new NotesModel(Note);
    await NoteDoc.save();
    res.send(Note);
  } catch (error) {
    res.status(500).send(error);
  }
};

exports.findOne = async (req, res) => {
  const id = req.params.id;

  try {
    let Note = await NotesModel.findById(id);
    res.send(Note);
  } catch (error) {
    res.status(500).send(error);
  }
};

exports.update = async (req, res) => {
  let { ...data } = req.body;
  const result = await NotesModel.findOneAndUpdate(
    { _id: req.params.id },
    data,
    {
      new: true,
    }
  );

  res.send(result);
};

exports.delete = async (req, res) => {
  try {
    let id = req.params.id;

    await NotesModel.findByIdAndDelete(req.params.id);

    res.status(200).send();
  } catch (error) {
    res.status(500).send(error);
  }
};
```
This part contains the logic for Creating, Reading, Updating and Deleting data from/to our database. Now in order for it to work, we've to bring it in routes file and map it to proper methods/paths. In order to do so, create a file called *index.js* inside **routes** folder and paste the following code:

```
// Bring in the express server
const express = require("express");

// Bring in the Express Router
const router = express.Router();

// Import the Controller
const controller = require("../controllers");

// Create a new Note
router.post("/", controller.create);

// Get all Notes
router.get("/", controller.findAll);

// Get Note by Id
router.get("/:id", controller.findOne);

// Modify existing Note
router.put("/:id", controller.update);

// Delete Note by Id
router.delete("/:id", controller.delete);

module.exports = router;
```

Now that all has been set-up, you can just run:
```
node server.js
```
The server will start and will listen to port:8080. You can use postman to test the APIs.

The complete project can be found on my  [Github](https://github.com/rajandmr/mongodb-nodejs-mongoose)