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
Contents
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:
– Show all objects:
– Click on Edit button to update an 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’:
MEVN stack CRUD App Architecture
We’re gonna build the application with following 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:
Methods | Urls | Actions |
---|---|---|
GET | api/tutorials | get all Tutorials |
GET | api/tutorials/:id | get Tutorial by id |
POST | api/tutorials | add new Tutorial |
PUT | api/tutorials/:id | update Tutorial by id |
DELETE | api/tutorials/:id | remove Tutorial by id |
DELETE | api/tutorials | remove all Tutorials |
GET | api/tutorials?title=[kw] | find all Tutorials which title contains 'kw' |
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:
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:
- create a new Tutorial: object.save()
- find a Tutorial by id: findById(id)
- retrieve all Tutorials: find()
- update a Tutorial by id: findByIdAndUpdate(id, data)
- remove a Tutorial: findByIdAndRemove(id)
- remove all Tutorials: deleteMany()
- find all Tutorials by title: find({ title: { $regex: new RegExp(title), $options: “i” } })
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
– 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
– 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')
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
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.
Source Code
You can find Github source code for this tutorial at: Vue + Node.js Github
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
Serverless with Firebase:
– Vue Firebase Realtime Database: CRUD example
– Vue Firestore: Build a CRUD App example
Happy learning, see you again!
Thank you
Hi there to all, I think every one is getting more knowledge and programming skill from your tutorials. Thanks!
Attractive fullstack tutorial!
This is really helpful MEVN tutorial. Thanks!
Hey there, thank you so much for the tutorial!
I like the helpful information you provide for your tutorials. Thanks!
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 😁
Thanks for sharing such a good tutorial. That’s why I have read it completely
Very well written fullstack MEVN Tutorial. Thanks!
Thanks for the good MEVN fullstack tutorial.
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.
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!
Hi, please look at where server.js file is placed 🙂
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.
Like!! Great tutorial. Really thank you! Really Cool.
Thank you for this MEVN tutorial, it helps me a lot! Keep up the good work!
Thank you so much for this fullstack Vue+ Node.js tutorial, simple but comprehensive.
Bookmarked!, I really like your full stack Vue Express with MongoDB tutorials!