Skip to main content

Building a RESTful CRUD API with Node.js, Express, MongoDB


Used Libraries

Express
Validator
Mongoose

_____________Just 3 Steps________________

Step 1

Initialize the project

npm init -y
npm install --save-dev nodemon
npm install express mongoose
npm install validator

Now go to the package.json and modifiy the scripts property like this.


Then create folder call utils and create a file call db.js inside it. Here is my project structure.


If  you haven't any idea to get MongoDB Connection String please refer first part from here.
Follow these set of code for RESTful API crud operations.

   Step 2

   db.js
const mongoose = require('mongoose');
const validator = require('validator');

const url = 'MongoDB Connection String';




mongoose.connect(url,{useUnifiedTopology:true,useNewUrlParser:true});


const Schema = mongoose.Schema;


const userSchema = new Schema({

    name : {
        type : String,
        require : true,
        trim : true
    },
    age : {
        type : Number,
        require : true,
        validate(value){
            if(value < 0){
                throw new Error('please enter valid age');
            }
        }
    },
    email : {
        type : String,
        require : true,
        validate(value){
            if(!validator.isEmail(value)){
                throw new Error('please enter valid email');
            }
        }
    },
    password : {
        type : String,
        require : true,
        minlength : 5
    }
});

const user = mongoose.model('User',userSchema);

module.exports = user;

   Step 3

   app.js
const express = require('express');
require('./utils/db');
const User = require('./utils/db');

const app = express();

app.use(express.json());

app.listen(3000);


//create user

app.post('/users',async(req,res)=>{ 
    const user1 = new User(req.body);
    try{
        await user1.save(); 
        res.status(201).send(user1);
    }
    catch(e){
        res.status(400).send(e.message);
    }
});

//fetch users

app.get('/users',async(req,res)=>{ 
    try{
        const users = await User.find({}); 
        if(!users){
            return res.status(404).send();
        }
        else{
            res.status(200).send(users);
        }
    }
    catch(e){
        res.status(400).send(e.message);
    }
});

//fetch user by id

app.get('/users/:id',async(req,res)=>{ 
    try{
        console.log(req.params);
        const user = await User.findById(req.params.id);

        if(!user){

            return res.status(404).send();
        }
        else{
            res.status(500).send(user);
        }
    }
    catch(e){
        res.status(400).send(e.message);
    }
});

//update user

app.patch('/users/:id',async(req,res)=>{ 
    try{
        console.log(req.params);
        const user = await User.findByIdAndUpdate(req.params.id,req.body,{new:true,runValidators:true});

        if(!user){

            return res.status(404).send();
        }
        else{
            res.status(200).send(user);
        }
    }
    catch(e){
        res.status(400).send(e.message);
    }
});


//delete user

app.delete('/users/:id',async(req,res)=>{ 
    try{
        console.log(req.params);
        const user = await User.findByIdAndDelete(req.params.id);

        if(!user){

            return res.status(404).send();
        }
        else{
            res.status(200).send(user);
        }
    }
    catch(e){
        res.status(400).send(e.message);
    }
});

Now you can run the project from npm run dev. okay cool.

Postman is a popular API client that makes it easy for developers to create, share, test and document APIs. This is done by allowing users to create and save simple and complex HTTP/s requests, as well as read their responses.

Use Postman and get better understand of basic concepts.

Comments

Post a Comment

Popular posts from this blog

Routing and navigation in Angular

Angular provides a complete  routing  library with the possibility to  have  multiple  router  outlets, different path matching strategies, easy access to  route  parameters and  route  guards to protect components from unauthorized access. The  Angular router is  a core part of the  Angular  platform. It's very easy to implement routing and navigation. So now I'm going to implement simple application for routing. When we create project it also create  app-routing.module.ts file. Then I created 2 components call DepartmentList and EmployeeList. So now what I want is when I Press the the Employee list button I want to move Employee List form and when press the Department list button  want to  move Department List form. First step You must go to the  app-routing.module.ts  and you can see there is an array call routes. Then declare your components with name which you want appear on URL.   Don't remember import your component. And you must export your components.

An Introduction to Mongoose, Express for MongoDB With NodeJS

This is about how to connect with MongoDB from NodeJS. Used Libraries Express  Mongoose Steps... 1. npm init -y 2. npm install --save-dev nodemon              coppy this inside package.json                 "scripts":{                   "start": "node app",                  "dev": "nodemon app"           } 3. npm i express mongoose db.js (Inside the utils folder) const mongoose = require('mongoose'); const validator = require('validator'); const url = 'MongoDB Connection String'; mongoose.connect(url,{useUnifiedTopology:true,useNewUrlParser:true}) .then(res => console.log(res)) .catch(err => console.log(err)); app.js const express = require('express'); require('./utils/db'); const app = express(); app.listen(3000);  For execute npm run dev