Skip to main content

REST API with Express and MongoDB

Creating a CRUD Rest Api example Express MongoDb:
 Step1: Creating application folder and application structure.:

 Step 2: Install required dependencies by using npm install < dependencies> --save command.
 Step 3: create app folder structure compatible with MVC structure as shown below.
 Package.json file should be like this:

 "scripts": { "start": "nodemon app.js" },
 "author": "", 
 "license": "ISC", 
 "dependencies": {
             "express": "^4.17.1", "mongoose": "^6.0.11", "nodemon": "^2.0.13" } }

 In app.js file write the code for the server: 

 const express = require('express'); 
const app = express(); 
const mongoose = require('mongoose'); 
 app.use(express.json()); // 
import routes const postRoute= require('./routes/posts'); 
app.use('/posts',postRoute); 

 //Routes // listening 

mongoose.connect("mongodb://localhost:27017/myowndb",() =>{ console.log("Connected to DB"); });

 app.listen(3000);  


In models/post.js file code: 
const mongoose = require('mongoose'); 
 const PostSchema= mongoose.Schema({ title:{ type:String, required:true, },
 description:{ type:String, required:true }, date:{ type:Date, default:Date.now } });

 module.exports=mongoose.model('Posts',PostSchema); 

 In routes/ posts.js file  code:

const express= require('express'); 
const router= express.Router();
 const Post= require('../models/post'); 
 // getting all posts router.get('/', async(req,res) =>{ try{ const posts = await Post.find(); res.json(posts);
 }catch (err){ res.json({message:err}); } });

 // getting a post by id

 router.get('/:postid', async(req,res) =>{ try{ const post = await Post.findById(req.params.postid); res.json(post); }catch(err){ res.json({message:err}); } })

 // creating a post

 router.post('/',(req,res)=>{ const post =new Post({ title:req.body.title, description:req.body.description }); post.save(). then(data =>{ res.json(data); }).catch (err=>{ res.json({message:err}); }) }); 

 // deleting a post

 router.delete('/:postid', async(req,res) =>{ try{ const removepost = await Post.deleteOne({_id: req.params.postid}); res.json(removepost); }catch(err){ res.json({message:err}); } } ); 

// updating a post by id

 router.patch('/:postid', async(req,res) =>{ try{ const editpost = await Post.updateOne({_id: req.params.postid}); res.json(editpost); }catch(err){ res.json({message:err}); } });

 module.exports= router;

Comments

  1. Thank you very much Charlie for your comments. I will always try to post some presentation on topics.

    ReplyDelete

Post a Comment

Popular posts from this blog

Docker Image AWS

SQL server

  Microsoft SQL Server: Microsoft SQL Server is a relational database management system (RDBMS). Applications and tools connect to a SQL Server instance or database, and communicate using Transact-SQL (T-SQL). You can install SQL Server on Windows or Linux, deploy it in a Linux container, or deploy it on an Azure Virtual Machine. SQL Server components and technologies: Database Engine The Database Engine is the core service for storing, processing, and securing data. The Database Engine provides controlled access and transaction processing to meet the requirements of the most demanding data consuming applications within your enterprise.  Integration Services SQL Server Integration Services (SSIS) is a platform for building high performance data integration solutions, including packages that provide extract, transform, and load (ETL) processing for data warehousing. Analysis Services SQL Server Analysis Services (SSAS) is an analytical data platform and toolset for personal, te...