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

Building a Responsive Weather App with React

 Fetching and Displaying Weather Data      By - ABDUL YESDANI Objective:  This document will help you prepare for the workshop on building a responsive weather app using React. You will learn the basics of React, how to use APIs, and how to work with data fetched from an API. By the end of the workshop, you’ll build a simple weather app that fetches real-time weather data.  1. What is React? React is a JavaScript library used to build user interfaces, especially for single-page applications. It lets you create components, which are reusable, isolated pieces of code that define a part of your user interface. Key Terms Component : Think of components as building blocks for your app. Each part of your app’s UI can be a component, like a button, form, or navigation bar. JSX : A syntax extension for JavaScript, which looks a lot like HTML. JSX is used to describe what the UI should look like. State : Data that controls what gets rendered on the screen. State can change over time, like inpu

.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.

node.js tutorial

node.js is a open source server environment. Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js is free,it is cross platform means runs on various platforms (Windows, Linux, Unix, Mac). Node.js uses JavaScript on the server.