DEV Community

Cover image for NodeJS CRUD API with MongoDB
Rajan Prasad
Rajan Prasad

Posted on

NodeJS CRUD API with MongoDB

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.


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 , 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:


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

Enter fullscreen mode Exit fullscreen mode

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:


Enter fullscreen mode Exit fullscreen mode

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");


const app = express();

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

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



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

let DB = process.env.DB;

  .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}`);

Enter fullscreen mode Exit fullscreen mode

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;

Enter fullscreen mode Exit fullscreen mode

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({});
  } catch (error) {
      message: error.message || "Some error occured while retrieving Notes",

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

  try {
    let NoteDoc = new NotesModel(Note);
  } catch (error) {

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

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

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


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

    await NotesModel.findByIdAndDelete(;

  } catch (error) {
Enter fullscreen mode Exit fullscreen mode

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"/", 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;
Enter fullscreen mode Exit fullscreen mode

Now that all has been set-up, you can just run:

node server.js
Enter fullscreen mode Exit fullscreen mode

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

Discussion (1)

cydonianllama profile image

Thanks, you made me understand the documentation...