Vue.js + Node.js + Express + MongoDB example: MEVN stack CRUD Application

In this tutorial, I will show you how to build a MEVN stack (Vue.js + Node.js + Express + MongoDB) example with a CRUD Application. The back-end server uses Node.js + Express for REST APIs, front-end side is a Vue client with Vue Router and axios.

More Practice: Node.js Express + Vue.js: JWT Authentication & Authorization example

Run both projects (back-end & front-end) in one place:
How to serve/combine Vue App with Express

Serverless with Firebase:
Vue Firebase Realtime Database: CRUD example
Vue Firestore: Build a CRUD App example


Vue.js + Node.js + Express + MongoDB example Overview

We will build a full-stack Tutorial Application in that:

  • Tutorial has id, title, description, published status.
  • User can create, retrieve, update, delete Tutorials.
  • There is a search box for finding Tutorials by title.

Here are screenshots of the example.

– Add an object:

vue-node-express-mongodb-crud-add-object

– Show all objects:

vue-node-express-mongodb-crud-show-objects

– Click on Edit button to update an object:

vue-node-express-mongodb-crud-edit-object

On this Page, you can:

  • change status to Published/Pending using Publish/UnPublished button
  • remove the object from MongoDB Database using Delete button
  • update this object’s details on Database with Update button

– Search objects by field ‘title’:

vue-node-express-mongodb-crud-search-objects

MEVN stack CRUD App Architecture

We’re gonna build the application with following architecture:

vue-node-express-mongodb-crud-mean-stack-architecture

– Node.js Express exports REST APIs & interacts with MongoDB Database using Mongoose ODM.
– Vue Client sends HTTP Requests and retrieves HTTP Responses using axios, consume data on the components. Vue Router is used for navigating to pages.

Node.js Express MongoDB Back-end

Overview

These are APIs that Node.js Express App will export:

MethodsUrlsActions
GETapi/tutorialsget all Tutorials
GETapi/tutorials/:idget Tutorial by id
POSTapi/tutorialsadd new Tutorial
PUTapi/tutorials/:idupdate Tutorial by id
DELETEapi/tutorials/:idremove Tutorial by id
DELETEapi/tutorialsremove all Tutorials
GETapi/tutorials?title=[kw]find all Tutorials which title contains 'kw'

Project Structure

vue-node-express-mongodb-crud-backend-project-structure

db.config.js exports configuring parameters for MongoDB connection & Mongoose.
Express web server in server.js where we configure CORS, initialize & run Express REST APIs.
– Next, we add configuration for MongoDB database in models/index.js, create Mongoose data model in models/tutorial.model.js.
– Tutorial controller in controllers.
– Routes for handling all CRUD operations (including custom finder) in tutorial.routes.js.

Implementation

Create Node.js App

First, we create a folder:

$ mkdir nodejs-express-mongodb
$ cd nodejs-express-mongodb

Next, we initialize the Node.js App with a package.json file:

npm init

name: (nodejs-express-mongodb) 
version: (1.0.0) 
description: Node.js Restful CRUD API with Node.js, Express and MongoDB
entry point: (index.js) server.js
test command: 
git repository: 
keywords: nodejs, express, mongodb, rest, api
author: bezkoder
license: (ISC)

Is this ok? (yes) yes

We need to install necessary modules: express, mongoose, body-parser and cors.
Run the command:

npm install express mongoose body-parser cors --save

Setup Express web server

In the root folder, let’s create a new server.js file:

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

const app = express();

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

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(bodyParser.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});

What we do are:
– import express, body-parser and cors modules:

  • Express is for building the Rest apis
  • body-parser helps to parse the request and create the req.body object
  • cors provides Express middleware to enable CORS with various options.

– create an Express app, then add body-parser and cors middlewares using app.use() method. Notice that we set origin: http://localhost:8081.
– define a GET route which is simple for test.
– listen on port 8080 for incoming requests.

Now let’s run the app with command: node server.js.
Open your browser with url http://localhost:8080/, you will see:

node-js-express-mongodb-example-setup-server

Yeah, the first step is done. We’re gonna work with Mongoose in the next section.

Configure MongoDB database & Mongoose

In the app folder, we create a separate config folder for configuration with db.config.js file like this:

module.exports = {
  url: "mongodb://localhost:27017/bezkoder_db"
};

Define Mongoose

We’re gonna define Mongoose model (tutorial.model.js) also in app/models folder in the next step.

Now create app/models/index.js with the following code:

const dbConfig = require("../config/db.config.js");

const mongoose = require("mongoose");
mongoose.Promise = global.Promise;

const db = {};
db.mongoose = mongoose;
db.url = dbConfig.url;
db.tutorials = require("./tutorial.model.js")(mongoose);

module.exports = db;

Don’t forget to call connect() method in server.js:

...
const app = express();
app.use(...);

const db = require("./app/models");
db.mongoose
  .connect(db.url, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  })
  .then(() => {
    console.log("Connected to the database!");
  })
  .catch(err => {
    console.log("Cannot connect to the database!", err);
    process.exit();
  });

Define the Mongoose Model

In models folder, create tutorial.model.js file like this:

module.exports = mongoose => {
  const Tutorial = mongoose.model(
    "tutorial",
    mongoose.Schema(
      {
        title: String,
        description: String,
        published: Boolean
      },
      { timestamps: true }
    )
  );

  return Tutorial;
};

This Mongoose Model represents tutorials collection in MongoDB database. These fields will be generated automatically for each Tutorial document: _id, title, description, published, createdAt, updatedAt, __v.

{
  "_id": "5e363b135036a835ac1a7da8",
  "title": "Js Tut#",
  "description": "Description for Tut#",
  "published": true,
  "createdAt": "2020-02-02T02:59:31.198Z",
  "updatedAt": "2020-02-02T02:59:31.198Z",
  "__v": 0
}

If you use this app with a front-end that needs id field instead of _id, you have to override toJSON method that map default object to a custom object. So the Mongoose model could be modified as following code:

module.exports = mongoose => {
  var schema = mongoose.Schema(
    {
      title: String,
      description: String,
      published: Boolean
    },
    { timestamps: true }
  );

  schema.method("toJSON", function() {
    const { __v, _id, ...object } = this.toObject();
    object.id = _id;
    return object;
  });

  const Tutorial = mongoose.model("tutorial", schema);
  return Tutorial;
};

And the result will look like this-

{
  "title": "Js Tut#",
  "description": "Description for Tut#",
  "published": true,
  "createdAt": "2020-02-02T02:59:31.198Z",
  "updatedAt": "2020-02-02T02:59:31.198Z",
  "id": "5e363b135036a835ac1a7da8"
}

After finishing the steps above, we don’t need to write CRUD functions, Mongoose Model supports all of them:

These functions will be used in our Controller.

Create the Controller

Inside app/controllers folder, let’s create tutorial.controller.js with these CRUD functions:

  • create
  • findAll
  • findOne
  • update
  • delete
  • deleteAll
  • findAllPublished
const db = require("../models");
const Tutorial = db.tutorials;

// Create and Save a new Tutorial
exports.create = (req, res) => {
  
};

// Retrieve all Tutorials from the database.
exports.findAll = (req, res) => {
  
};

// Find a single Tutorial with an id
exports.findOne = (req, res) => {
  
};

// Update a Tutorial by the id in the request
exports.update = (req, res) => {
  
};

// Delete a Tutorial with the specified id in the request
exports.delete = (req, res) => {
  
};

// Delete all Tutorials from the database.
exports.deleteAll = (req, res) => {
  
};

// Find all published Tutorials
exports.findAllPublished = (req, res) => {
  
};

You can continue with step by step to implement this Node.js Express App in the post:
Node.js, Express & MongoDb: Build a CRUD Rest Api example

Run the Node.js Express Server

Run our Node.js application with command: node server.js.

Vue.js Front-end

Overview

vue-node-express-mysql-example-vue-client-overview

– The App component is a container with router-view. It has navbar that links to routes paths.

TutorialsList component gets and displays Tutorials.
Tutorial component has form for editing Tutorial’s details based on :id.
AddTutorial component has form for submission new Tutorial.

– These Components call TutorialDataService methods which use axios to make HTTP requests and receive responses.

Technology

  • vue: 2.6.10
  • vue-router: 3.1.3
  • axios: 0.19.0

Project Structure

vue-node-express-mysql-example-vue-client-project-structure

package.json contains 3 main modules: vue, vue-router, axios.
– There are 3 components: TutorialsList, Tutorial, AddTutorial.
router.js defines routes for each component.
http-common.js initializes axios with HTTP base Url and headers.
TutorialDataService has methods for sending HTTP requests to the Apis.
vue.config.js configures port for this Vue Client.

Implementation

Setup Vue.js Project

Open cmd at the folder you want to save Project folder, run command:
vue create vue-js-client-crud

You will see some options, choose default (babel, eslint).
After the process is done. We create new folders and files like the following tree:


public

index.html

src

components

AddTutorial.vue

Tutorial.vue

TutorialsList.vue

services

TutorialDataService.js

App.vue

main.js

package.json


Open public/index.html, add bootstrap inside <head> tag:

<!DOCTYPE html>
<html lang="en">
  <head>
    ...
    <title>vue-js-client-crud</title>
    <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
  </head>
  <body>
    ...
  </body>
</html>

Add Vue Router to Vue.js 2 CRUD App

– Run the command: npm install vue-router.

– In src folder, create router.js and define Router as following code:

import Vue from "vue";
import Router from "vue-router";

Vue.use(Router);

export default new Router({
  mode: "history",
  routes: [
    {
      path: "/",
      alias: "/tutorials",
      name: "tutorials",
      component: () => import("./components/TutorialsList")
    },
    {
      path: "/tutorials/:id",
      name: "tutorial-details",
      component: () => import("./components/Tutorial")
    },
    {
      path: "/add",
      name: "add",
      component: () => import("./components/AddTutorial")
    }
  ]
});

– Open src/main.js, then import router:

import Vue from 'vue'
import App from './App.vue'
import router from './router'

Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App),
}).$mount('#app')

Add Navbar and Router View to Vue.js 2 CRUD App

Let’s open src/App.vue, this App component is the root container for our application, it will contain a navbar.

<template>
  <div id="app">
    <nav class="navbar navbar-expand navbar-dark bg-dark">
      <router-link to="/" class="navbar-brand">bezKoder</router-link>
      <div class="navbar-nav mr-auto">
        <li class="nav-item">
          <router-link to="/tutorials" class="nav-link">Tutorials</router-link>
        </li>
        <li class="nav-item">
          <router-link to="/add" class="nav-link">Add</router-link>
        </li>
      </div>
    </nav>

    <div class="container mt-3">
      <router-view />
    </div>
  </div>
</template>

<script>
export default {
  name: "app"
};
</script>

Initialize Axios for Vue.js 2 CRUD HTTP Client

Now we’re gonna install axios with command: npm install axios.
Then, under src folder, we create http-common.js file like this:

import axios from "axios";

export default axios.create({
  baseURL: "http://localhost:8080/api",
  headers: {
    "Content-type": "application/json"
  }
});

Remember to change the baseURL, it depends on REST APIs url that your Server configures.

Create Data Service

Our service will use axios from HTTP client above to send HTTP requests.

services/TutorialDataService.js

import http from "../http-common";

class TutorialDataService {
  getAll() {
    return http.get("/tutorials");
  }

  get(id) {
    return http.get(`/tutorials/${id}`);
  }

  create(data) {
    return http.post("/tutorials", data);
  }

  update(id, data) {
    return http.put(`/tutorials/${id}`, data);
  }

  delete(id) {
    return http.delete(`/tutorials/${id}`);
  }

  deleteAll() {
    return http.delete(`/tutorials`);
  }

  findByTitle(title) {
    return http.get(`/tutorials?title=${title}`);
  }
}

export default new TutorialDataService();

Create Vue Components

As I’ve said before, we have 3 components corresponding to 3 routes defined in Vue Router.

  • Add new Item
  • List of items
  • Item details

You can continue with step by step to implement this Vue App in the post:
Vue.js CRUD App with Vue Router & Axios

Or using Vuetify: Vuetify data-table example with a CRUD App

vuetify-data-table-example-crud-app-retrieve-all

Run Vue.js Client

You can run our Vue App with command: npm run serve.
If the process is successful, open Browser with Url: http://localhost:8081/ and check it.

Conclusion

Now we have an overview of Vue.js + Node.js Express + MongoDB example when building a MEVN stack CRUD App.

We also take a look at client-server architecture for REST API using Express & Mongoose ODM, as well as Vue.js project structure for building a front-end app to make HTTP requests and consume responses.

Next tutorials show you more details about how to implement the system:

Run both projects (back-end & front-end) in one place:
How to serve/combine Vue App with Express

If you want a Typescript version for the Vue App, it is here:
Vue Typescript CRUD Application to consume Web API example

Pagination:
Server side Pagination in Node.js, MongoDB | Mongoose Paginate v2
Vue Pagination with Axios and API (Server Side pagination) example

vue-pagination-axios-api-bootstrap-vue-page-change

Serverless with Firebase:
Vue Firebase Realtime Database: CRUD example
Vue Firestore: Build a CRUD App example

Happy learning, see you again!

14 thoughts to “Vue.js + Node.js + Express + MongoDB example: MEVN stack CRUD Application”

  1. I enjoy what you guys are usually up too. This type of tutorial!
    Keep up the amazing works guys I’ve added you guys to my personal blogroll.

  2. Please check the code in server.js.

    I think
    >const db = require(“./app/models”);
    is not correct.

    const db = require(“./models”);

    is correct.

    Please tell me your answer.

    1. I had a mistake a folder location of app.
      After I changed the place of app folder, I succeed!
      Thank you to create this page!
      I am very happy!

  3. I’ve not followed the tutorial but I’m already excited at the content.

    Great job you’re doing, keep it up KIU!

    PS: Bookmarked 😁

Leave a Reply

Your email address will not be published. Required fields are marked *