Make api in express js
1. app.js
import express from 'express'
import connectDb from './db/connectdb.js'
import web from './routes/web.js'
const app = express()
const port = process.env.PORT || '3000'
const Database_url = process.env.Database_url || "mongodb://localhost:27017"
//json
app.use(express.json())
connectDb(Database_url)
app.use('/student',web)
app.listen(port,()=>{
console.log('Server Connected Successfully.')
})
2.web.js
import express from 'express'
import studentController from '../controllers/studentController.js'
const router = express.Router()
router.get('/',studentController.getAllDoc)
router.post('/',studentController.createDoc)
router.get('/:id',studentController.getSingleDocById)
router.put('/:id',studentController.updateDocById)
router.delete('/:id',studentController.deleteDocById)
export default router
3.Student.js
import mongoose from "mongoose"
//Defining Schema
const studentSchema = new mongoose.Schema({
name:{type:String,required:true,trim:true},
age:{type:Number,required:true},
fees:{type:mongoose.Decimal128,required:true,validate:(value)=> value >= 5000.50}
})
//Creating Model
const studentModel = mongoose.model("student",studentSchema)
export default studentModel
4.studentController.js
import studentModel from "../models/Student.js"
class studentController {
static createDoc = async(req,res)=>{
try{
//first way to store data
const {name,age,fees} = req.body //destructure
const doc = new studentModel ({
name:name,
age:age,
fees:fees
})
const result = await doc.save()
res.send(result)
}catch(error){
console.log(error);
}
}
static getAllDoc = async(req,res)=>{
try{
const result = await studentModel.find()
res.send(result)
}catch(error){
console.log(error);
}
}
static getSingleDocById = async (req,res)=>{
try{
const result = await studentModel.findById(req.params.id)
res.send(result)
}catch(error){
console.log(error);
}
}
static updateDocById = async (req,res)=>{
try{
const result = await studentModel.findByIdAndUpdate(req.params.id,req.body)
res.send(result)
}catch(error){
console.log(error);
}
}
static deleteDocById = async (req,res)=>{
try{
const result = await studentModel.findByIdAndDelete(req.params.id)
res.status(204).send(result)
}catch(error){
console.log(error);
}
}
}
export default studentController
Comments
Post a Comment