These are the middleware needed for CRUD operations in express
Enable CORS
Connect to the database
Create models
Filter users using querystring
Fetch users using ID
Use bodyparser to allow express to read the body and parse it into JSON object
validate post method using PostMan
Validate using fiddler
Validate put operation using postman
In this example we need to delete the is from the parser as we cannot update the id.
Validate patch in postman
Update document in the collection
Validated delete in postman
Updated user collection in DB
//web framework for node.js var express= require('express') //Gives an instance of express var app=express(); //Used for post request and forms var bodyParser=require('body-parser'); //MongoDB Object modeling tool designed to work in asynchronous environment var mongoose = require('mongoose');
Enable CORS
//Enable cors app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type,
Accept"); next(); });
Connect to the database
//connect to mongoose mongoose.connect('mongodb://127.0.0.1:27017/Ecommerce');
Create models
//Model for fetching users var userSchema=mongoose.Schema({ firstName:{ type:String, required:true }, lastName:{ type:String } }); //User Model var User=mongoose.model("users",userSchema)
GET
Find all users using Get//Using find to fetch all the users in the db app.get("/api/Users",function(req,res){ User.find({},function (err,user){ if(err) { console.log(err); res.send(err); } else { console.log(user); res.send(user);} }); });
Filter users using querystring
app.get("/api/Users",function(req,res){ //Get the filter query var query=req.query; User.find(query, function(err, user) { if (err) res.send(err); else res.send(user) //res.json(user); }); });
Fetch users using ID
app.use('/api/Users/:_id',function(req,res,next){ console.log('custom middleware'); //Find based on ID User.findById(req.params._id, function(err, user) { if (err) res.status(500).send(err); //fetch user and send it to next function else if(user) { req.user=user; next(); res.status(200).send('Success'); } else { res.status(404).send('no user found'); } }); });
Use bodyparser to allow express to read the body and parse it into JSON object
//Use bodyParser app.use(bodyParser.urlencoded({extended:true})); app.use(bodyParser.json());
POST
Post to save new users//Post app.post('/api/Users',function(req, res) { var users = new User(req.body); //save users users.save(function(err) { //Check for error if (err) { return res.send(err); } else{ console.log('Success'); res.send(users) } }); //res.send('Responding');*/ });
validate post method using PostMan
Validate using fiddler
PUT
Find the specified document and update the record/** * PUT */ app.put('/api/Users/:_id',function(req,res){ //Get the filter query User.findById(req.params._id, function(err, user) { if(err) { res.send(err); } //Update else { user.firstName=req.body.firstName; user.lastName=req.body.lastName; user.save(function(err) { if (err) { return res.send(err); } else{ console.log('Edit Succeded'); res.send(users) } }); res.json(user) } }); });
Validate put operation using postman
Updated document in the collection.
PATCH
The HTTP methods PATCH can be used to update partial resources
/** * PATCH */ app.patch('/api/Users/:_id',function(req,res){ //We do not want ot update the ID. We need to delete ID from the body parser if(req.body._id) { delete req.body_id; } //Fetch all the keys in the body parser for(var u in req.body){ //assignind the body content to the req object req.user[u]=req.body[u]; } req.user.save(function(err){ if (err) res.status(500).send(err); //fetch user and send it to next function else { res.json(req.user); } }); });
Validate patch in postman
Update document in the collection
DELETE
For delete we need to use the remove function./** * DELETE */ app.delete('/api/Users/:_id',function(req,res){ //delete the document frmom the mongodb collection req.user.remove(); });
Validated delete in postman
Updated user collection in DB
No comments:
Post a Comment