{"id":205,"date":"2019-11-23T13:40:34","date_gmt":"2019-11-23T13:40:34","guid":{"rendered":"http:\/\/localhost\/blogs\/?p=205"},"modified":"2020-12-28T09:37:12","modified_gmt":"2020-12-28T09:37:12","slug":"mevn-stack-for-beginners","status":"publish","type":"post","link":"https:\/\/www.appfinz.com\/blogs\/mevn-stack-for-beginners\/","title":{"rendered":"MEVN Stack For Beginners"},"content":{"rendered":"\n<p><strong>MEVN Stack Tutorial From Scratch is today topic,  We will generate \nFullStack Single Page Application(SPA) using Mongo, MongoDB, Express, \nVue, and Node<\/strong><\/p>\n\n\n\n<p>In\n this post, we learn a simple CRUD operation where the user can create, \nread, delete and update some data.so let us start the MEVN Stack \nTutorial From Scratch for&nbsp;the beginner.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">MEVN Stack Tutorial From Scratch for beginner<\/h3>\n\n\n\n<p>Before start tutorials, we need to first \ninstall Vue.js project using Vue CLI and for install CLI we need Node.js\n (version 8.9 or above&nbsp; 8.11.0+ recommended)<\/p>\n\n\n\n<p>Run the following command to install Vue CLI, if you have not installed in your machine.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code> npm install -g @vue\/cli\n\n # OR\n\n yarn global add @vue\/cli<\/code><\/pre>\n\n\n\n<p> After successfully&nbsp;install you can check the version is Vue js using this command. <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>vue --version\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Step: 1 Create a new Vue.js project<\/h2>\n\n\n\n<p>Run this&nbsp;following command to install&nbsp;<strong>Vue.js.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>vue create mevnproject<\/code><\/pre>\n\n\n\n<p> It takes some time to depend on your internet speed. <\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"824\" height=\"366\" src=\"https:\/\/appfinz.com\/blogs\/wp-content\/uploads\/2019\/11\/index.png\" alt=\"\" class=\"wp-image-210\" title=\"\" srcset=\"https:\/\/www.appfinz.com\/blogs\/wp-content\/uploads\/2019\/11\/index.png 824w, https:\/\/www.appfinz.com\/blogs\/wp-content\/uploads\/2019\/11\/index-300x133.png 300w, https:\/\/www.appfinz.com\/blogs\/wp-content\/uploads\/2019\/11\/index-768x341.png 768w\" sizes=\"auto, (max-width: 824px) 100vw, 824px\" \/><\/figure>\n\n\n\n<p> Now, go to your Vue js project folder and run following command. <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code> cd mevnexample<\/code><\/pre>\n\n\n\n<p> After that start the Vue js dev server using the following command.&nbsp; <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npm run serve<\/code><\/pre>\n\n\n\n<p> Now, open project file in your favorite code editor. <\/p>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/appfinz.com\/blogs\/wp-content\/uploads\/2019\/11\/index-1.png\" alt=\"\" class=\"wp-image-211\" width=\"539\" height=\"203\" title=\"\" srcset=\"https:\/\/www.appfinz.com\/blogs\/wp-content\/uploads\/2019\/11\/index-1.png 407w, https:\/\/www.appfinz.com\/blogs\/wp-content\/uploads\/2019\/11\/index-1-300x113.png 300w\" sizes=\"auto, (max-width: 539px) 100vw, 539px\" \/><\/figure>\n\n\n\n<p>Go to the&nbsp;<strong>http:\/\/localhost:8081 URL&nbsp;<\/strong> on your browser.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step:2&nbsp;&nbsp;Install Vue dependencies.<\/h2>\n\n\n\n<p>We install two dependencies one is&nbsp;<strong>vue-router&nbsp;<\/strong>and&nbsp;<strong>vue-axios.<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Vue-router :&nbsp;<\/strong>&nbsp;Vue router use for routing in our Vue js applicaion.<\/li><li><strong>Vue-axios&nbsp;:&nbsp;<\/strong> V-axios use for sending the network request severe.<\/li><\/ul>\n\n\n\n<p>Install this dependency using following this command.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code> npm install axios vue-router vue-axios --save<\/code><\/pre>\n\n\n\n<p>In this Vue application, we use the bootstrap framework for styling. to install bootstrap run this command.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npm install bootstrap --save<\/code><\/pre>\n\n\n\n<p>Now import&nbsp;bootstrap file in <strong>main.js<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code> \/\/ main.js  Created By Appfinz\n\nimport Vue from 'vue'\nimport App from '.\/App.vue'\nimport 'bootstrap\/dist\/css\/bootstrap.min.css'\n\nVue.config.productionTip = false\n\nnew Vue({\n  render: h =&gt; h(App),\n}).$mount('#app')<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Step 3: Create some components in Vue js&nbsp;<\/h2>\n\n\n\n<p>In&nbsp;<strong>src\/components&nbsp;<\/strong>folder create four new following components.<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>HomeComponent.vue<\/li><li>CreateComponent.vue<\/li><li>EditComponent.vue<\/li><li>IndexComponent.vue<\/li><\/ol>\n\n\n\n<p>Now, add some view code inside the&nbsp;<strong>HomeComponent.vue&nbsp;<\/strong>file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code> &lt;template&gt;\n  &lt;div class=\"row justify-content-center\"&gt;\n      &lt;div class=\"col-md-8\"&gt;\n          &lt;div class=\"card card-default\"&gt;\n              &lt;div class=\"card-header\"&gt;Home Component&lt;\/div&gt;\n\n              &lt;div class=\"card-body\"&gt;\n                  I'm the Home Component component.\n              &lt;\/div&gt;\n          &lt;\/div&gt;\n      &lt;\/div&gt;\n  &lt;\/div&gt;\n &lt;\/template&gt;\n &lt;script&gt;\n export default {\n }\n &lt;\/script&gt;<\/code><\/pre>\n\n\n\n<p>After adding this component we need to import the&nbsp;<strong>HomeComponent.vue&nbsp;<\/strong>file inside the&nbsp;<strong>App.vue&nbsp;<\/strong>file.<\/p>\n\n\n\n<p>Visit&nbsp;http:\/\/localhost:8081\/ to see <strong>HomeComponents <\/strong>rendering.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"897\" height=\"231\" src=\"https:\/\/appfinz.com\/blogs\/wp-content\/uploads\/2019\/11\/index-2.png\" alt=\"\" class=\"wp-image-212\" title=\"\" srcset=\"https:\/\/www.appfinz.com\/blogs\/wp-content\/uploads\/2019\/11\/index-2.png 897w, https:\/\/www.appfinz.com\/blogs\/wp-content\/uploads\/2019\/11\/index-2-300x77.png 300w, https:\/\/www.appfinz.com\/blogs\/wp-content\/uploads\/2019\/11\/index-2-768x198.png 768w\" sizes=\"auto, (max-width: 897px) 100vw, 897px\" \/><\/figure>\n\n\n\n<p>Now create other three components.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>CreatComponent.vue<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code> &lt;template&gt;\n  &lt;div class=\"row justify-content-center\"&gt;\n      &lt;div class=\"col-md-8\"&gt;\n          &lt;div class=\"card card-default\"&gt;\n              &lt;div class=\"card-header\"&gt;Create Component&lt;\/div&gt;\n\n              &lt;div class=\"card-body\"&gt;\n                  I'm the Create Component component.\n              &lt;\/div&gt;\n          &lt;\/div&gt;\n      &lt;\/div&gt;\n  &lt;\/div&gt;\n &lt;\/template&gt;\n\n &lt;script&gt;\n  export default {\n  }\n &lt;\/script&gt;<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>EditComponent.vue<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code> \/\/ EditComponent.vue\n\n &lt;template&gt;\n  &lt;div class=\"row justify-content-center\"&gt;\n      &lt;div class=\"col-md-8\"&gt;\n          &lt;div class=\"card card-default\"&gt;\n              &lt;div class=\"card-header\"&gt;Edit Component&lt;\/div&gt;\n\n              &lt;div class=\"card-body\"&gt;\n                  I'm an Edit component.\n              &lt;\/div&gt;\n          &lt;\/div&gt;\n      &lt;\/div&gt;\n  &lt;\/div&gt;\n &lt;\/template&gt;\n \n &lt;script&gt;\n  export default {\n  }\n &lt;\/script&gt;<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>IndexComponent.vue<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code> \/\/ IndexComponent.vue\n\n &lt;template&gt;\n  &lt;div class=\"row justify-content-center\"&gt;\n      &lt;div class=\"col-md-8\"&gt;\n          &lt;div class=\"card card-default\"&gt;\n              &lt;div class=\"card-header\"&gt;Index Component&lt;\/div&gt;\n\n              &lt;div class=\"card-body\"&gt;\n                  I'm an Index component.\n              &lt;\/div&gt;\n          &lt;\/div&gt;\n      &lt;\/div&gt;\n  &lt;\/div&gt;\n &lt;\/template&gt;\n\n &lt;script&gt;\n  export default {\n  }\n &lt;\/script&gt;<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Step:4 Configure the Vue-router<\/h2>\n\n\n\n<p>Now, configure Vue&nbsp;router.&nbsp;Inside the&nbsp;<strong>main.js&nbsp;<\/strong>file, write the following code for the route.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ main.js\n\nimport Vue from 'vue'\nimport App from '.\/App.vue'\nimport 'bootstrap\/dist\/css\/bootstrap.min.css'\n\nimport VueRouter from 'vue-router';\nVue.use(VueRouter);\n\nVue.config.productionTip = false;\n\nimport HomeComponent from '.\/components\/HomeComponent.vue';\nimport CreateComponent from '.\/components\/CreateComponent.vue';\nimport IndexComponent from '.\/components\/IndexComponent.vue';\nimport EditComponent from '.\/components\/EditComponent.vue';\n\nconst routes = &#91;\n  {\n      name: 'home',\n      path: '\/',\n      component: HomeComponent\n  },\n  {\n      name: 'create',\n      path: '\/create',\n      component: CreateComponent\n  },\n  {\n      name: 'posts',\n      path: '\/posts',\n      component: IndexComponent\n  },\n  {\n      name: 'edit',\n      path: '\/edit\/:id',\n      component: EditComponent\n  }\n];\n\nconst router = new VueRouter({ mode: 'history', routes: routes});\n\nnew Vue(Vue.util.extend({ router }, App)).$mount('#app');\n<\/code><\/pre>\n\n\n\n<p>Here,&nbsp;first import the Vue-router module and create an array for the route which has a <strong>name, path,<\/strong>&nbsp;and <strong>components&nbsp;<\/strong>as the properties.<\/p>\n\n\n\n<p>After that, we have created the router object and passed the mode history and routes array.<\/p>\n\n\n\n<p>Now, the at the last step is to define the&nbsp;<strong>&lt;router-view&gt;&lt;\/router-view&gt;&nbsp;<\/strong>element in the view. It renders the component according to the routing path in our Vue application.<\/p>\n\n\n\n<p>So, add the&nbsp;<strong>&lt;router-view&gt;&nbsp;<\/strong>inside the&nbsp;<strong>App.vue&nbsp;<\/strong>file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ App.vue\n\n&lt;template&gt;\n  &lt;div&gt;\n    &lt;router-view&gt;&lt;\/router-view&gt;\n  &lt;\/div&gt;\n&lt;\/template&gt;\n\n&lt;script&gt;\n\n\nexport default {\n  name: 'app'\n}\n&lt;\/script&gt;<\/code><\/pre>\n\n\n\n<p>Now, save the file and check the following route paths.<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>http:\/\/localhost:8080\/create<\/li><li>http:\/\/localhost:8080\/posts<\/li><li>http:\/\/localhost:8080\/edit\/1<\/li><\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Step:4 Create nav-bar for Vue application.<\/h2>\n\n\n\n<p>Write the following code inside the&nbsp;<strong>App.vue&nbsp;<\/strong>file for Nav bar.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ App.vue\n\n&lt;template&gt;\n  &lt;div class=\"container\"&gt;\n    &lt;nav class=\"navbar navbar-expand-sm bg-dark navbar-dark\"&gt;\n      &lt;ul class=\"navbar-nav\"&gt;\n        &lt;li class=\"nav-item\"&gt;\n          &lt;router-link to=\"\/\" class=\"nav-link\"&gt;Home&lt;\/router-link&gt;\n        &lt;\/li&gt;\n        &lt;li class=\"nav-item\"&gt;\n          &lt;router-link to=\"\/create\" class=\"nav-link\"&gt;Create Post&lt;\/router-link&gt;\n        &lt;\/li&gt;\n        &lt;li class=\"nav-item\"&gt;\n          &lt;router-link to=\"\/posts\" class=\"nav-link\"&gt;Posts&lt;\/router-link&gt;\n        &lt;\/li&gt;\n      &lt;\/ul&gt;\n    &lt;\/nav&gt;&lt;br \/&gt;\n    &lt;transition name=\"fade\"&gt;\n      &lt;router-view&gt;&lt;\/router-view&gt;\n    &lt;\/transition&gt;\n  &lt;\/div&gt;\n&lt;\/template&gt;\n\n&lt;style&gt;\n   \n&lt;\/style&gt;\n\n&lt;script&gt;\n\n    export default{\n    }\n&lt;\/script&gt;\n<\/code><\/pre>\n\n\n\n<p>Here we add some code navigation bar for Vue application.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step:6 Create a form in&nbsp;<strong>CreateComponent.vue<\/strong><\/h2>\n\n\n\n<p>We need a simple form for submitting data. so let&#8217;s create a form in&nbsp;<strong>CreateComponent.vue<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ CreateComponent.vue\n\n&lt;template&gt;\n  &lt;div&gt;\n    &lt;h1&gt;Create A Post&lt;\/h1&gt;\n    &lt;form @submit.prevent=\"addPost\"&gt;\n      &lt;div class=\"row\"&gt;\n        &lt;div class=\"col-md-6\"&gt;\n          &lt;div class=\"form-group\"&gt;\n            &lt;label&gt;Post Title:&lt;\/label&gt;\n            &lt;input type=\"text\" class=\"form-control\" v-model=\"post.title\"&gt;\n          &lt;\/div&gt;\n        &lt;\/div&gt;\n        &lt;\/div&gt;\n        &lt;div class=\"row\"&gt;\n          &lt;div class=\"col-md-6\"&gt;\n            &lt;div class=\"form-group\"&gt;\n              &lt;label&gt;Post Body:&lt;\/label&gt;\n              &lt;textarea class=\"form-control\" v-model=\"post.body\" rows=\"5\"&gt;&lt;\/textarea&gt;\n            &lt;\/div&gt;\n          &lt;\/div&gt;\n        &lt;\/div&gt;&lt;br \/&gt;\n        &lt;div class=\"form-group\"&gt;\n          &lt;button class=\"btn btn-primary\"&gt;Create&lt;\/button&gt;\n        &lt;\/div&gt;\n    &lt;\/form&gt;\n  &lt;\/div&gt;\n&lt;\/template&gt;\n\n&lt;script&gt;\n    export default {\n        data(){\n        return {\n          post:{}\n        }\n    },\n    methods: {\n      addPost(){\n        console.log(this.post);\n      }\n    }\n  }\n&lt;\/script&gt;\n<\/code><\/pre>\n\n\n\n<p>First, at the bottom of the code, we define the object&nbsp;<strong>post&nbsp;<\/strong>here use used two-way data binding the post object has two properties title and body.<\/p>\n\n\n\n<p>Second, we create one method called&nbsp;<strong>addPost().&nbsp;<\/strong>when the user submits form details we will receive inside the&nbsp;<strong>addPost()&nbsp;<\/strong> method. we will send a POST method request to the Laravel server and to save the data into the database.<\/p>\n\n\n\n<p>Save all files and go to this URL:&nbsp;<strong>http:\/\/localhost:8080\/create&nbsp;<\/strong>You can see the form like below.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"941\" height=\"577\" src=\"https:\/\/appfinz.com\/blogs\/wp-content\/uploads\/2019\/11\/index-3.png\" alt=\"\" class=\"wp-image-214\" title=\"\" srcset=\"https:\/\/www.appfinz.com\/blogs\/wp-content\/uploads\/2019\/11\/index-3.png 941w, https:\/\/www.appfinz.com\/blogs\/wp-content\/uploads\/2019\/11\/index-3-300x184.png 300w, https:\/\/www.appfinz.com\/blogs\/wp-content\/uploads\/2019\/11\/index-3-768x471.png 768w\" sizes=\"auto, (max-width: 941px) 100vw, 941px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Step: 7 Create a Node.js backend<\/h2>\n\n\n\n<p>Create a new folder inside the Vue project root called&nbsp;<strong>API&nbsp;<\/strong>and go inside that new folder.<\/p>\n\n\n\n<p>And now, initialize the&nbsp;<strong>package.json&nbsp;<\/strong>file.&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npm init -y<\/code><\/pre>\n\n\n\n<p>After running this command inside the new folder a new file auto created named&nbsp;<strong>package.json.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  \"name\": \"api\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" &amp;&amp; exit 1\"\n  },\n  \"keywords\": &#91;],\n  \"author\": \"\",\n  \"license\": \"ISC\"\n}\n<\/code><\/pre>\n\n\n\n<p>After that install the following&nbsp;<strong>node.js<\/strong>&nbsp;dependencies.&nbsp; using the following command.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>yarn add express body-parser cors mongoose\n\n# or\n\nnpm install express body-parser cors mongoose --save<\/code><\/pre>\n\n\n\n<p>We need to also install&nbsp;<strong>Nodemon serve&nbsp;<\/strong>as a development dependency. because we do not need to restart every time, we change our server code.e change our server code.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npm install nodemon --save-dev<\/code><\/pre>\n\n\n\n<p>Now we need to&nbsp;create some files called&nbsp;<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><strong>server.js<\/strong><\/li><li><strong>DB.js<\/strong><\/li><li><strong>post.model.js<\/strong><\/li><li><strong>post.route.js.&nbsp;<\/strong><\/li><\/ol>\n\n\n\n<p>All these files should be inside the root of the&nbsp;<strong>API&nbsp;<\/strong>folder. and write the following code inside the&nbsp;<strong>server.js&nbsp;<\/strong>file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ server.js\n\nconst express = require('express');\nconst app = express();\nconst bodyParser = require('body-parser');\nconst PORT = 4000;\nconst cors = require('cors');\n\napp.use(cors());\napp.use(bodyParser.urlencoded({extended: true}));\napp.use(bodyParser.json());\n\napp.listen(PORT, function(){\n  console.log('Server is running on Port:',PORT);\n});\n<\/code><\/pre>\n\n\n\n<p>After that, we need to start a node server using the following command.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>nodemon server<\/code><\/pre>\n\n\n\n<p>After running the command, our node.js server is running at port:&nbsp;<strong>4000<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"353\" height=\"156\" src=\"https:\/\/appfinz.com\/blogs\/wp-content\/uploads\/2019\/11\/index-4.png\" alt=\"\" class=\"wp-image-215\" title=\"\" srcset=\"https:\/\/www.appfinz.com\/blogs\/wp-content\/uploads\/2019\/11\/index-4.png 353w, https:\/\/www.appfinz.com\/blogs\/wp-content\/uploads\/2019\/11\/index-4-300x133.png 300w\" sizes=\"auto, (max-width: 353px) 100vw, 353px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Step:8 install and connect with MongoDB Database<\/h2>\n\n\n\n<p>Install MongoDB in your computer system. here&nbsp;I am just using the terminal for this demo because it is a simple application.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>mongod<\/code><\/pre>\n\n\n\n<p>Inside the API, folder creates a new file&nbsp;<strong>DB.js for&nbsp;<\/strong>connecting our node application&nbsp;with MongoDB, so this following code inside the&nbsp;<strong>DB.js.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ DB.js\n\nmodule.exports = {\n    DB: 'mongodb:\/\/localhost:27017\/mevncrud'\n}<\/code><\/pre>\n\n\n\n<p>For the local MongoDB server, username and password may be empty. but\n when we create a production database we need to set all this thing.<\/p>\n\n\n\n<p>Now, import this&nbsp;<strong>DB.js<\/strong>&nbsp;file into&nbsp;the<strong>&nbsp;server.js&nbsp;<\/strong>file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ server.js\n\nconst express = require('express');\nconst app = express();\nconst bodyParser = require('body-parser');\nconst PORT = 4000;\nconst cors = require('cors');\nconst mongoose = require('mongoose');\nconst config = require('.\/DB.js');\n\nmongoose.Promise = global.Promise;\nmongoose.connect(config.DB, { useNewUrlParser: true }).then(\n  () =&gt; {console.log('Database is connected') },\n  err =&gt; { console.log('Can not connect to the database'+ err)}\n);\n\napp.use(cors());\napp.use(bodyParser.urlencoded({extended: true}));\napp.use(bodyParser.json());\n\napp.listen(PORT, function(){\n  console.log('Server is running on Port:',PORT);\n});<\/code><\/pre>\n\n\n\n<p>Now, our application connects with MongoDB Database.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step:9&nbsp;Create a Mongoose Schema<\/h2>\n\n\n\n<p>Add some code inside the&nbsp;<strong>post.model.js<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ post.model.js\n\nconst mongoose = require('mongoose');\nconst Schema = mongoose.Schema;\n\n\/\/ Define collection and schema for Post\nlet Post = new Schema({\n  title: {\n    type: String\n  },\n  body: {\n    type: String\n  }\n},{\n    collection: 'posts'\n});\n\nmodule.exports = mongoose.model('Post', Post);\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Step:10 Create Routes for Node.js application<\/h2>\n\n\n\n<p>Here we add&nbsp;CRUD operation code inside the&nbsp;<strong>post.route.js&nbsp;<\/strong>file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ post.model.js\n\nconst express = require('express');\nconst postRoutes = express.Router();\n\n\/\/ Require Post model in our routes module\nlet Post = require('.\/post.model');\n\n\/\/ Defined store route\npostRoutes.route('\/add').post(function (req, res) {\n  let post = new Post(req.body);\n  post.save()\n    .then(() =&gt; {\n      res.status(200).json({'business': 'business in added successfully'});\n    })\n    .catch(() =&gt; {\n      res.status(400).send(\"unable to save to database\");\n    });\n});\n\n\/\/ Defined get data(index or listing) route\npostRoutes.route('\/').get(function (req, res) {\n    Post.find(function(err, posts){\n    if(err){\n      res.json(err);\n    }\n    else {\n      res.json(posts);\n    }\n  });\n});\n\n\/\/ Defined edit route\npostRoutes.route('\/edit\/:id').get(function (req, res) {\n  let id = req.params.id;\n  Post.findById(id, function (err, post){\n      if(err) {\n        res.json(err);\n      }\n      res.json(post);\n  });\n});\n\n\/\/  Defined update route\npostRoutes.route('\/update\/:id').post(function (req, res) {\n    Post.findById(req.params.id, function(err, post) {\n    if (!post)\n      res.status(404).send(\"data is not found\");\n    else {\n        post.title = req.body.title;\n        post.body = req.body.body;\n        post.save().then(() =&gt; {\n          res.json('Update complete');\n      })\n      .catch(() =&gt; {\n            res.status(400).send(\"unable to update the database\");\n      });\n    }\n  });\n});\n\n\/\/ Defined delete | remove | destroy route\npostRoutes.route('\/delete\/:id').delete(function (req, res) {\n    Post.findByIdAndRemove({_id: req.params.id}, function(err){\n        if(err) res.json(err);\n        else res.json('Successfully removed');\n    });\n});\n\nmodule.exports = postRoutes;<\/code><\/pre>\n\n\n\n<p>Inside the post model js, we write the CRUD operation in Node.js \nwhich is back end server side. so when a user requests from the \nclientside hits the node express server and the above function will be \nexecuted&nbsp;and all request sends to the&nbsp;database and send the response to \nthe client, in this application we use vue.js as frontend.<\/p>\n\n\n\n<p>We use MongoDB ORM to CRUD operation from the MongoDB database.&nbsp;<strong>Mongoose&nbsp;<\/strong>is an <strong>ORM(Object Relational Mapping) <\/strong>which is&nbsp;used in&nbsp;<strong>the MongoDB<\/strong>&nbsp;database. Now, we have&nbsp;all setup for&nbsp;the CRUD operations set up on the&nbsp;<strong>post.route.js&nbsp;<\/strong>file. we need to import inside the&nbsp;<strong>server.js&nbsp;<\/strong>file.<\/p>\n\n\n\n<p>So, our finally&nbsp;<strong>server.js&nbsp;<\/strong>file looks like this.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ server.js\n\nconst express = require('express');\nconst app = express();\nconst bodyParser = require('body-parser');\nconst PORT = 4000;\nconst cors = require('cors');\nconst mongoose = require('mongoose');\nconst config = require('.\/DB.js');\nconst postRoute = require('.\/post.route');\n\nmongoose.Promise = global.Promise;\nmongoose.connect(config.DB, { useNewUrlParser: true }).then(\n  () =&gt; { console.log('Database is connected') },\n  err =&gt; { console.log('Can not connect to the database'+ err)}\n);\n\napp.use(cors());\napp.use(bodyParser.urlencoded({extended: true}));\napp.use(bodyParser.json());\n\napp.use('\/posts', postRoute);\n\napp.listen(PORT, function(){\n  console.log('Server is running on Port:',PORT);\n});<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Step:12&nbsp;Use Axios to send a network request<\/h2>\n\n\n\n<p>&nbsp;Import the&nbsp;<strong>axios&nbsp;<\/strong>and&nbsp;<strong>vue-axios&nbsp;<\/strong>in the&nbsp;<strong>main.js&nbsp;<\/strong>file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ main.js\n\nimport Vue from 'vue'\nimport App from '.\/App.vue'\nimport 'bootstrap\/dist\/css\/bootstrap.min.css'\n\nimport VueRouter from 'vue-router';\nVue.use(VueRouter);\n\nimport VueAxios from 'vue-axios';\nimport axios from 'axios';\n\nVue.use(VueAxios, axios);\n\nVue.config.productionTip = false;\n\nimport HomeComponent from '.\/components\/HomeComponent.vue';\nimport CreateComponent from '.\/components\/CreateComponent.vue';\nimport IndexComponent from '.\/components\/IndexComponent.vue';\nimport EditComponent from '.\/components\/EditComponent.vue';\n\nconst routes = &#91;\n  {\n      name: 'home',\n      path: '\/',\n      component: HomeComponent\n  },\n  {\n      name: 'create',\n      path: '\/create',\n      component: CreateComponent\n  },\n  {\n      name: 'posts',\n      path: '\/posts',\n      component: IndexComponent\n  },\n  {\n      name: 'edit',\n      path: '\/edit\/:id',\n      component: EditComponent\n  }\n];\n\nconst router = new VueRouter({ mode: 'history', routes: routes});\n\nnew Vue(Vue.util.extend({ router }, App)).$mount('#app');\n<\/code><\/pre>\n\n\n\n<p>We have created the backend. Next step is to send the&nbsp;<strong>POST method<\/strong>&nbsp;request to the node.js API server. Remember, now we have three servers are running.<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Vue development server<\/li><li>Node.js server<\/li><li>MongoDB server<\/li><\/ol>\n\n\n\n<p>Make sure, all these running fine otherwise the project won\u2019t work.<\/p>\n\n\n\n<p>Write some code code inside the&nbsp;<strong>CreateComponent.vue&nbsp;<\/strong>file\u2019s&nbsp;<strong>addPost()&nbsp;<\/strong>function.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ CreateComponent.vue\n\naddPost(){\n    let uri = 'http:\/\/localhost:4000\/posts\/add';\n    this.axios.post(uri, this.post).then(() =&gt; {\n       this.$router.push({name: 'posts'});\n    });\n}<\/code><\/pre>\n\n\n\n<p>Now we can create the post and see in the MongoDB database.<\/p>\n\n\n\n<p>To check by the terminal, you need to open the mongo shell using the following command.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>mongo<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Step:12&nbsp;Display the backend data<\/h2>\n\n\n\n<p>After saving a row of data into database we want to display. so write some code inside the IndexComponent.vue<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ IndexComponent.js\n\n&lt;template&gt;\n  &lt;div&gt;\n      &lt;h1&gt;Posts&lt;\/h1&gt;\n        &lt;div class=\"row\"&gt;\n          &lt;div class=\"col-md-10\"&gt;&lt;\/div&gt;\n          &lt;div class=\"col-md-2\"&gt;\n            &lt;router-link :to=\"{ name: 'create' }\" class=\"btn btn-primary\"&gt;Create Post&lt;\/router-link&gt;\n          &lt;\/div&gt;\n        &lt;\/div&gt;&lt;br \/&gt;\n\n        &lt;table class=\"table table-hover\"&gt;\n            &lt;thead&gt;\n            &lt;tr&gt;\n              &lt;th&gt;Title&lt;\/th&gt;\n              &lt;th&gt;Body&lt;\/th&gt;\n              &lt;th&gt;Actions&lt;\/th&gt;\n            &lt;\/tr&gt;\n            &lt;\/thead&gt;\n            &lt;tbody&gt;\n                &lt;tr v-for=\"post in posts\" :key=\"post._id\"&gt;\n                  &lt;td&gt;{{ post.title }}&lt;\/td&gt;\n                  &lt;td&gt;{{ post.body }}&lt;\/td&gt;\n                  &lt;td&gt;&lt;router-link :to=\"{name: 'edit', params: { id: post._id }}\" class=\"btn btn-primary\"&gt;Edit&lt;\/router-link&gt;&lt;\/td&gt;\n                  &lt;td&gt;&lt;button class=\"btn btn-danger\"&gt;Delete&lt;\/button&gt;&lt;\/td&gt;\n                &lt;\/tr&gt;\n            &lt;\/tbody&gt;\n        &lt;\/table&gt;\n  &lt;\/div&gt;\n&lt;\/template&gt;\n\n&lt;script&gt;\n  export default {\n      data() {\n        return {\n          posts: &#91;]\n        }\n      },\n      created() {\n      let uri = 'http:\/\/localhost:4000\/posts';\n      this.axios.get(uri).then(response =&gt; {\n        this.posts = response.data;\n      });\n    }\n  }\n&lt;\/script&gt;<\/code><\/pre>\n\n\n\n<p>Now you can see this inserted data on the browser.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step:13&nbsp;Send edit and update request<\/h2>\n\n\n\n<p>Now, when we want to edit our data we need to fetch that record from data to display on view. Then, after editing the data in the&nbsp;<strong>textbox<\/strong>&nbsp;and&nbsp;<strong>textarea<\/strong>, when&nbsp;we hit the update button,&nbsp;<strong>updatePost()&nbsp;<\/strong>function to send a post request to the server to update the data.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ EditComponent.vue\n\n&lt;template&gt;\n  &lt;div&gt;\n    &lt;h1&gt;Edit Post&lt;\/h1&gt;\n    &lt;form @submit.prevent=\"updatePost\"&gt;\n      &lt;div class=\"row\"&gt;\n        &lt;div class=\"col-md-6\"&gt;\n          &lt;div class=\"form-group\"&gt;\n            &lt;label&gt;Post Title:&lt;\/label&gt;\n            &lt;input type=\"text\" class=\"form-control\" v-model=\"post.title\"&gt;\n          &lt;\/div&gt;\n        &lt;\/div&gt;\n        &lt;\/div&gt;\n        &lt;div class=\"row\"&gt;\n          &lt;div class=\"col-md-6\"&gt;\n            &lt;div class=\"form-group\"&gt;\n              &lt;label&gt;Post Body:&lt;\/label&gt;\n              &lt;textarea class=\"form-control\" v-model=\"post.body\" rows=\"5\"&gt;&lt;\/textarea&gt;\n            &lt;\/div&gt;\n          &lt;\/div&gt;\n        &lt;\/div&gt;&lt;br \/&gt;\n        &lt;div class=\"form-group\"&gt;\n          &lt;button class=\"btn btn-primary\"&gt;Update&lt;\/button&gt;\n        &lt;\/div&gt;\n    &lt;\/form&gt;\n  &lt;\/div&gt;\n&lt;\/template&gt;\n\n&lt;script&gt;\n    export default {\n\n      data() {\n        return {\n          post: {}\n        }\n      },\n      created() {\n        let uri = `http:\/\/localhost:4000\/posts\/edit\/${this.$route.params.id}`;\n        this.axios.get(uri).then((response) =&gt; {\n            this.post = response.data;\n        });\n      },\n      methods: {\n        updatePost() {\n          let uri = `http:\/\/localhost:4000\/posts\/update\/${this.$route.params.id}`;\n          this.axios.post(uri, this.post).then(() =&gt; {\n            this.$router.push({name: 'posts'});\n          });\n        }\n      }\n    }\n&lt;\/script&gt;<\/code><\/pre>\n\n\n\n<p>After changing the database we can&nbsp;see the edit data from the database and also you can update the database.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step:14 Delete the data<\/h2>\n\n\n\n<p>So, add some final code inside the&nbsp;<strong>IndexComponent.vue&nbsp;<\/strong>file for delete a record.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ IndexComponent.vue\n\n&lt;template&gt;\n  &lt;div&gt;\n      &lt;h1&gt;Posts&lt;\/h1&gt;\n        &lt;div class=\"row\"&gt;\n          &lt;div class=\"col-md-10\"&gt;&lt;\/div&gt;\n          &lt;div class=\"col-md-2\"&gt;\n            &lt;router-link :to=\"{ name: 'create' }\" class=\"btn btn-primary\"&gt;Create Post&lt;\/router-link&gt;\n          &lt;\/div&gt;\n        &lt;\/div&gt;&lt;br \/&gt;\n\n        &lt;table class=\"table table-hover\"&gt;\n            &lt;thead&gt;\n            &lt;tr&gt;\n              &lt;th&gt;Title&lt;\/th&gt;\n              &lt;th&gt;Body&lt;\/th&gt;\n              &lt;th&gt;Actions&lt;\/th&gt;\n            &lt;\/tr&gt;\n            &lt;\/thead&gt;\n            &lt;tbody&gt;\n                &lt;tr v-for=\"post in posts\" :key=\"post._id\"&gt;\n                  &lt;td&gt;{{ post.title }}&lt;\/td&gt;\n                  &lt;td&gt;{{ post.body }}&lt;\/td&gt;\n                  &lt;td&gt;&lt;router-link :to=\"{name: 'edit', params: { id: post._id }}\" class=\"btn btn-primary\"&gt;Edit&lt;\/router-link&gt;&lt;\/td&gt;\n                  &lt;td&gt;&lt;button class=\"btn btn-danger\" @click.prevent=\"deletePost(post._id)\"&gt;Delete&lt;\/button&gt;&lt;\/td&gt;\n                &lt;\/tr&gt;\n            &lt;\/tbody&gt;\n        &lt;\/table&gt;\n  &lt;\/div&gt;\n&lt;\/template&gt;\n\n&lt;script&gt;\n  export default {\n      data() {\n        return {\n          posts: &#91;]\n        }\n      },\n      created() {\n      let uri = 'http:\/\/localhost:4000\/posts';\n      this.axios.get(uri).then(response =&gt; {\n        this.posts = response.data;\n      });\n    },\n    methods: {\n      deletePost(id)\n      {\n        let uri = `http:\/\/localhost:4000\/posts\/delete\/${id}`;\n        this.axios.delete(uri).then(response =&gt; {\n          this.posts.splice(this.posts.indexOf(id), 1);\n        });\n      }\n    }\n  }\n&lt;\/script&gt;\n<\/code><\/pre>\n\n\n\n<p>Save all file, and now, you can see delete the values from the&nbsp;<strong>MongoDB<\/strong>&nbsp;database.<\/p>\n\n\n\n<p>So, finally, our <strong>MEVN Stack For Beginners\u00a0<\/strong>is over.\u00a0<\/p>\n\n\n\n<p>Tags:&nbsp;<a href=\"https:\/\/appfinz.com\/\" target=\"_blank\" rel=\"noreferrer noopener\">website development company in delhi<\/a>||&nbsp;<a href=\"https:\/\/appfinz.com\/website-development\/custom-website-development\">website designing company in delhi<\/a>&nbsp;||&nbsp;<a href=\"https:\/\/appfinz.com\/website-development\/web-portal-development\">b2b portal development company<\/a>&nbsp;||&nbsp;<a href=\"https:\/\/appfinz.com\/ecommerce\/magento-development\">magento development company in delhi<\/a>&nbsp;||&nbsp;&nbsp;<a href=\"https:\/\/appfinz.com\/website-designing\/website-redesigning\">website redesigning company in delhi<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>MEVN Stack Tutorial From Scratch is today topic, We will generate FullStack Single Page Application(SPA)<\/p>\n","protected":false},"author":1,"featured_media":234,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[26],"tags":[],"class_list":["post-205","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-nodejs"],"_links":{"self":[{"href":"https:\/\/www.appfinz.com\/blogs\/wp-json\/wp\/v2\/posts\/205","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.appfinz.com\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.appfinz.com\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.appfinz.com\/blogs\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.appfinz.com\/blogs\/wp-json\/wp\/v2\/comments?post=205"}],"version-history":[{"count":9,"href":"https:\/\/www.appfinz.com\/blogs\/wp-json\/wp\/v2\/posts\/205\/revisions"}],"predecessor-version":[{"id":803,"href":"https:\/\/www.appfinz.com\/blogs\/wp-json\/wp\/v2\/posts\/205\/revisions\/803"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.appfinz.com\/blogs\/wp-json\/wp\/v2\/media\/234"}],"wp:attachment":[{"href":"https:\/\/www.appfinz.com\/blogs\/wp-json\/wp\/v2\/media?parent=205"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.appfinz.com\/blogs\/wp-json\/wp\/v2\/categories?post=205"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.appfinz.com\/blogs\/wp-json\/wp\/v2\/tags?post=205"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}