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

What is Angular?

What is Angular? Angular is a TypeScript-based open-source web application framework led by the Angular Team at Google. Angular is a complete rewrite from the same team that built AngularJS. For now it's stable release is 8.2.14. What is the difference between Angular and AngularJs? Basically Angular is based on TypeScript. AngularJs  is based on JavaScript. What is TypeScript? TypeScript is an open-source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript, and adds optional static typing to the language. TypeScript is designed for development of large applications and transcompiles to JavaScript. What is JavaScript? JavaScript, often abbreviated as JS, is a high-level, just-in-time compiled, multi-paradigm programming language that conforms to the ECMAScript specification. JavaScript has curly-bracket syntax, dynamic typing, prototype-based object-orientation, and first-class functions. Why we need...

Simply NodeJS Introduction

NodeJS Is Opensource cross platform run time environment for developing server side web application. It runs on google's V8 JavaScript engine. NodeJS Is Not Another web framework. It is a module of JavaScript. For beginners. Multi thread. What is unique about NodeJS Server side module. Servers are normally thread based. But NodeJS is event based. NodeJS programs are executed by V8  JavaScript Engine the same used by Google Chrome browser.        

JSON Web Token Introduction

JSON Web Token Introduction JSON Web Token (JWT) is an open standard that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the  HMAC  algorithm) or a public/private key pair using  RSA  or  ECDSA . When should you use JSON Web Tokens? Authorization : This is the most comm on sce nario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains. Information Exchange : JSON Web Tokens are a good way of securely transmitting information between parties. Because JWTs can be signed—for example, using public/p...