Full Post Page
 

NodeJs API-MVC-2

Category: NODE JS & Written by Admin On June-02-2025 10:56:22

WHAT IS API Application Program Interface NodeJs websites Android Application __API___ MongoDB,mysql Swift iphone app API ---Data json/XML/GRAPHQL MOSTLY USE JSON IN API EXPRESSJS NodeJs API DEVELOPMENT READ app.get('/profile',(req,res)=>{}) Create app.post('/profile',(req,res)=>{}) Update app.put('/profile',(req,res)=>{}) Delete app.delete('/profile',(req,res)=>{}) notes But work with HTML use only post ,get But Show Your data Use method res.json() middleware app.use(express.json()) need command npm init -y npm install express nodemon mongoose npm install dotenv package.js dotenv": "^16.5.0", "express": "^5.1.0", "mongoose": "^8.15.1", "nodemon": "^3.1.10" create index.js create.models,routes folder files add in index.js const studentRouterfiles=require('./routes/students.routes') add in routes folder module.exports=router const StudentsModel=require('../models/students.model') open command mongosh show dbs ,use students-crud,show collections db.mystudentcolls.insertOne({ first_name:"Rupesh", last_name:'tech', email:'admin@admin.com', phone:"67465456564", gender:"male" }) db.mystudentcolls.insertOne({ first_name:"sajan", last_name:'kumar', email:'sajan@admin.com', phone:"9965456564", gender:"male" }) open POSTMEN M-Get localhost:3000/api/students // see data all M-Get localhost:3000/api/students/683a961a0a98305151b71236//single data M-POSt localhost:3000/api/students/ select params-body-form-urlencoded enter key and value M-PUT localhost:3000/api/students/683ac39fcb3f1618b4f05571 select params-body-form-urlencoded enter key and value ======================done==== MVC folder Seprate Code short for server files created .env npm install dotenv create .env files here IS PORT =3000 MONGO_URL='mongodb://127.0.0.1:27017/students-crud ' create config folder and here database.js const express = require('express'); const mongoose=require('mongoose') const dotenv=require('dotenv') dotenv.config() const connectDB=()=>{ mongoose.connect(process.env.MONGO_URL) .then(()=>console.log("connected mongo")) .catch(err=>console.log(err)) } // EXPORTS THIS module.exports=connectDB // do import in index js index.js const express = require('express'); const app = express(); // const mongoose=require('mongoose') also include in database const studentRouterfiles=require('./routes/students.routes') // router files import here and this route declare midleware also /* separte in folder database mongoose.connect('mongodb://127.0.0.1:27017/students-crud' .then(()=>console.log("connected mongo")) .catch(err=>console.log(err)) } */ // database all // import this and call connectdb const connectDB=require('./config/database') connectDB() const PORT=process.env.PORT // parse application/x-www-form-urlencoded app.use(express.urlencoded({ extended: false })) // middleware app.use(express.json()) // route midllware name =>app.use(routename/topic_api_name,Yourdefine_routefilesname) app.use('/api/students', studentRouterfiles) // app.listen(3000, () => { // console.log('Server running on port 3000'); // }); app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); }); route/students,routes.js const express=require('express') // use Router method for myroutes const router=express.Router() // add Your model folder const StudentsModel=require('../models/students.model') /* Now create Your Route using Router method using error handing try{ }catch(err){ } */ // 1. See All data router.get('/',async(req,res)=>{ try{ const students_fetchall=await StudentsModel.find() res.json(students_fetchall) }catch(err){ res.status(500).json({message:err.message}) } }) // 3. See single data router.get('/:id',async(req,res)=>{ try{ const students_singledata=await StudentsModel.findById(req.params.id) // id se value lene ke lie req,params.id use krte h //before check data come or not may be id wrong if(!students_singledata) return res.status(404).json({message:'students not found'}) res.json(students_singledata) }catch(err){ res.status(500).json({message:err.message}) } }) // 2. add new data router.post('/',async(req,res)=>{ try{ const newStudent=await StudentsModel.create(req.body) res.status(201).json(newStudent) }catch(err){ res.status(400).json({message:err.message}) } }) // 4. update All data // { new: true} para latest value show krta h router.put('/:id',async(req,res)=>{ try{ const updateStudent=await StudentsModel.findByIdAndUpdate(req.params.id,req.body,{ new: true}) if(!updateStudent) return res.status(404).json({message:'students not found'}) res.json(updateStudent) }catch(err){ res.status(500).json({message:err.message}) } }) // 5. Delete data router.delete('/:id',async(req,res)=>{ try{ const delstudent=await StudentsModel.findByIdAndDelete(req.params.id) if(!delstudent) return res.status(404).json({message:'students not found'}) res.json( {message:'student Deleted'}) }catch(err){ res.status(500).json({message:err.message}) } }) //module export route in index.js files and import in index.js module.exports=router models/students.model.js // create define schema const mongoose=require('mongoose') const studentSchema=new mongoose.Schema({ first_name: { type : String, require: true }, last_name: { type : String, require: true }, email: { type : String, require: true, unique: true }, phone: { type : String, require: true }, gender: { type : String, enum: ['Male','Female','Other'], require: true }, profile_pic: { type : String } }) // create collection name .YourSchema const Student =mongoose.model('mystudentColl',studentSchema) //Studnts var export module.exports=Student

Comments

Share your thoughts about this post

Why Choose Us:

Experienced Instructors: Our team of experienced instructors are passionate about coding and dedicated to helping you succeed. With years of industry experience and a knack for teaching, they'll guide you every step of the way. Beginner-Friendly Content: Don't worry if you're new to coding. Our tutorials are designed with beginners in mind, starting from the fundamentals and gradually building up to more advanced topics. Updated Content: Coding is a rapidly evolving field, and we're committed to keeping our content up-to-date with the latest trends, technologies, and best practices. Community Support: Learning to code is more fun and effective when you're part of a supportive community. Join our online community forums to connect with fellow learners, share insights, and collaborate on projects. Get Started Today:



Recent Posts

Advance Js Fetch API Part-5

June-06-2025 21:23:08


Advance Js Promise Part-4

June-06-2025 11:35:05


Advance js oop part-3

June-06-2025 08:25:42


ExpressJs API With Image Crud-3

June-02-2025 21:09:41


NodeJs API-MVC-2

June-02-2025 10:56:22


ExpressJs API Crud-1

June-02-2025 10:27:58


ExpressJs Files upload

June-02-2025 10:15:40


NodeJS Cookie and CsrfToken

May-30-2025 19:20:40


ExpressJS Session

May-30-2025 19:14:29


ExpressJS NodeJs Crud Part-2

May-27-2025 21:52:18


ExpressJS NodeJS Crud Part-1

May-27-2025 21:33:30


ExpressJS Authentication

May-26-2025 17:11:41


NodeJS ExpressJS Files Upload

May-26-2025 16:53:29



Angular Introduction

May-13-2025 21:02:32



Advance Js part-1

May-12-2025 15:41:29