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

Every day Hands on Exercises / Assignments

Day wise hands on exercises/ assignments Day 1: HTML Hands on Exercises Date:04-10-2021 1.Create a web page to display your name, designation, location. 2. Create a web page to show about yourself in 3, 4 paragraphs. 3. Create a web page to display some nature images and Describe those images. 4.create a web page about college anniversary celebrations Divide your page in 4, 5 div elements . In the 1st div, put the heading of college , and display other details about the college. In the second div put images of the college. In third div put details of celebrations in paragraphs In the fourth div display the guest list. Use style attribute for doing color, background color, font etc, To emphasise some special content use elements like , 5. Create a web app on Indian cultural festivals. Use semantic elements for lay out of the page. Define an external style sheet and link with the page. Your app should have indexpage, cultural page, about us page. You should navigate amon...

.Net Presentation

.NET is a free, cross-platform, open source developer platform for building many different types of applications. With .NET, you can use multiple languages, editors, and libraries to build for web, mobile, desktop, games, and IoT. You can write .NET apps in C#, F#, or Visual Basic. C# is a simple, modern, object-oriented, and type-safe programming language. F# is a programming language that makes it easy to write succinct, robust, and performant code. Visual Basic is an approachable language with a simple syntax for building type-safe, object-oriented apps. You can write .NET apps in C#, F#, or Visual Basic. C# is a simple, modern, object-oriented, and type-safe programming language. F# is a programming language that makes it easy to write succinct, robust, and performant code. Visual Basic is an approachable language with a simple syntax for building type-safe, object-oriented apps.

AWS Cloud Computing

Before the inception of Cloud Computing platforms, businesses predominantly relied on servers, databases, hardware, software, and other peripherals to take their businesses online. Companies had to buy these components to ensure that their website or applications reached the users. Besides, businesses also needed a team of experts to manage the hardware and software, and to monitor the infrastructure. While this approach was practical, it came with its unique issues, like the high cost of setup, complex components, and limited storage space, to name a few. Cloud Computing was created to address these problems. Cloud Computing is a network of remote servers hosted on the internet for storing and retrieving data. The cloud provides a number of IT services such as servers, databases, software, virtual storage, and networking, among others. In layman’s terms, Cloud Computing is defined as a virtual platform that allows you to store and access your data over the internet without any limit...