Simple REST API using Express, & MongoDB -Project Implementation
In the previous post i described how to setup the project in order to move onto the project implementation to create a REST API using Express and MongoDB.
And now let's dive into the fun part
First we will be implementing the server.js
require('dotenv').config()
const express = require('express');
const app = express();
const mongooes = require('mongoose');
mongooes.connect(process.env.DB_URL,
{ useUnifiedTopology: true })
const db = mongooes.connection
db.on('error',(error) => console.log(error))
db.once('open',()=>console.log('Connected to DB'))
app.use(express.json())
const subscriberRouter = require('./routes/users')
app.use('/users',subscriberRouter)
app.listen(3000, () => console.log('Server started'))
Initially we need to require the all necessary dependencies. Then the DB connection is needed to be created. Next it is required to define a middleware using express to recognize all incoming Request object as JSON. Next the required route is needed to be defined.Next, we will be implementing the users.js inside the model folder.
const mongoose = require('mongoose')
const userSchema = mongoose.Schema({
name:{
type :String,
require: true
},
subscriberToChannel:{
type :String,
require: true
},
subscriberDate:{
type:Date,
required:true,
default:Date.now
}
})
module.exports = mongoose.model('users',userSchema)
Finally, we will be implementing the users.js inside the routes folder.
const express = require('express')
const router = express.Router()
const User = require('../models/users')
// Getting all users
router.get('/',async (req,res) =>{
try{
const users = await User.find()
res.json(users)
}catch (err){
res.status(500).json({message:err.message})
}
})
//Getting one user
router.get('/:id',getUser,(req,res)=>{
res.send(res.user.name)
})
//creating one user
router.post('/',async(req,res)=>{
const user = new User({
name:req.body.name,
subscriberToChannel:req.body.subscriberToChannel
})
try{
const newUser = await user.save()
res.status(201).json(newUser)
}catch(err){
res.status(400).json({msg:err.message})
}
})
//updating a user
router.patch('/:id',getUser,async (req,res)=>{
if(req.body.name !=null){
res.user.name = req.body.name
}
if(req.body.subscriberToChannel!=null){
res.user.subscriberToChannel = req.body.subscriberToChannel
}
try{
const updatedUser = await res.user.save()
res.json(updatedUser)
}catch(err){
res.status(400).json({msg:err.message})
}
})
//deleting a user
router.delete('/:id',getUser, async(req,res)=>{
try{
await res.user.remove();
res.json({msg:'Deleted Succesfully'})
}catch(err){
res.status(500).json({msg:err.message})
}
})
async function getUser(req,res,next){
let user
try{
user = await User.findById(req.params.id)
if(user == null){
return res.status(404).json({msg:'Cannot find subscriber'})
}
}catch (err){
return res.status(500).json({msg:err.message})
}
res.user = user
next()
}
module.exports = router
0 comments :
Post a Comment