Docker Cheat Sheet

docker --version
docker version

Dockerfile

FROM php:7-apache
COPY . /var/www/html
WORKDIR /var/www/html
#CMD php index.php
EXPOSE 80
docker build -t helloworldphp7 .

To run docker image

docker run -p 8080:80 -v /c/xampp/htdocs/dockerdemo:/var/www/html -d php:8-apache

OR

docker run -p 8080:80 --name docker-apache -v /c/xampp/htdocs/dockerdemo:/var/www/html:ro -d php:8-apache

OR

docker run -d -p 8080:8080 --name jsp-project -v /root/jsp/:/usr/local/tomcat/webapps/test tomcat:9.0.1-jre8-alpine

To run docker image in interactive mode

docker container run -it <docker-image> /bin/bash

To List all images

docker images
docker images -q

To List all container

docker ps
docker ps -a
docker ps -aq

To remove image

docker rmi imagename

OR

docker rmi $(docker images -aq)

To remove container

docker rm <container-name>

OR

docker rm $(docker ps -aq)

OR

docker rm -f $(docker ps -aq)

To stop container

docker stop <container-name>

OR

docker stop $(docker ps -aq)

To push local image on docker hub

First create repository in dockerhub like we used to create in gitlab/github

docker login
docker tag firstimage YOUR_DOCKERHUB_NAME/firstimage
docker images
docker push YOUR_DOCKERHUB_NAME/firstimage

Working with MySQL

docker pull mysql/mysql-server:latest
docker images
docker create -v /var/lib/mysql --name mysqldata mysql/mysql-server:latest
docker ps -a
docker run -p 3307:3307 -d -e MYSQL_ROOT_PASSWORD=root --volumes-from mysqldata --name=mysqldb1 mysql/mysql-server:latest
docker ps
docker exec -it mysqldb1 bash
mysql -uroot -p

Install Jenkins on Ubuntu

sudo apt update
sudo apt install default-jdk default-jre
javac
wget -q -O - https://pkg.jenkins.io/debian/jenkins.io.key | sudo apt-key add -
sudo sh -c "echo deb http://pkg.jenkins.io/debian-stable binary/ > /etc/apt/sources.list.d/jenkins.list"
sudo apt update
sudo apt install jenkins
sudo service jenkins start
sudo service jenkins status

Open Browser and hit following url

http://localhost:8080/

To view default initial password

sudo cat /var/lib/jenkins/secrets/initialAdminPassword

Install recommended Plugins. Make sure Git Plugin is installed

Username: admin
Password: Shift + 5
Full name: Administrator

Jenkins URL: http://localhost:8080/
Or
http://youripaddress:8080/
Or
http://yourdomain:8080/

Create New Item (New project for build)

Create release_project.sh file

rsync -av --exclude-from='.releaseignore' <src_dir_path> <dest_dir_path>

Add files and directories entries in .releaseignore file to skip rsync

node_modules
.git
private_documents

After creating freestyle project if you face any permission issue then try one of the following solutions

sudo su -
vim /etc/sudoers

Add following entry at end of file

#add jenkins as sudoer
jenkins        ALL=(ALL)       NOPASSWD: ALL

OR add user to the group

sudo usermod -a -G sudo jenkins

Ref:
medium.com
stackoverflow

vim cheat sheet

to open file

vim filename

copy/cut paste

yy => p
dd => p
v => select lines to copy => y => goto line where need to paste => p
v => select lines to cut => d => goto line where need to paste => p

to undo and redo

Esc
u u u u 

Esc
Ctrl + R Ctrl + R

to open file in read mode

vim -R filename

to open file on specific line number

vim filename +10

insert mode

i
o

escape / command mode

Esc

to write file

:w
:wq
:x

to minimize vim editor

Ctrl + Z

to see minimized files in vim

jobs

to see background job

bg

to open specific jobs or bring it to foreground

fg 1
fg +
fg -

search any word in vim editor

/word
/word\c
/word\C
#then press N or Shift + N

search and replace word

:%s/word/replacewith/i
:%s/word/replacewith/g

go to specific line

:10
:1
:$

show/hide line numbers in vim editor

:set number
:set nonumber

set tabstop

:set tabstop=4

set font color

:colorscheme murphy

vimdiff difference between 2 files

vimdiff file1 file2
#difference put
dp
#difference obtain
do

SQL Cheat Sheet

login to database

mysql -u username -p'password' database_name

logout from database

Ctrl + D

list all database

SHOW DATABASES;

Create Database

CREATE DATABASE company;

enter database

USE database_name;

show current database (dual is dummy/virtual database provided by oracle)

SELECT DATABASE() FROM dual;

list all tables

SHOW TABLES;

list table pattern

SHOW TABLES LIKE '%table_substring%';

Create table

CREATE TABLE users(
    id INT,
    NAME VARCHAR(100) NOT NULL,
    age TINYINT NOT NULL,
    city VARCHAR(200) NOT NULL
);

Alter table

ALTER TABLE
    users MODIFY id INT PRIMARY KEY AUTO_INCREMENT;
ALTER TABLE
    users ADD added_at DATETIME AFTER `city`,
    ADD updated_at DATETIME AFTER added_at;

show schema

DESC <table_name>;
SHOW CREATE TABLE <table_name>\G;

show running sql processes

SHOW FULL PROCESSLIST;

import database/table (RUN IN BASH TERMINAL)
NOTE: Make sure your database is present in mysql server if not create new one

mysql -u root -p'password' database_name < backup_file.sql

export database (all tables) (RUN IN BASH TERMINAL)

mysqldump -u root -p'password' database_name > backup_file.sql

export specific tables (RUN IN BASH TERMINAL)

mysqldump -u root -p'password' database_name tbl1 tbl2 tbl3 > backup_file.sql

export only schema without data

mysqldump -u root -p'password' database_name --no-data 

run sql command in terminal

mysql -u root -p'password' -e "SELECT COUNT(*) FROM database_name.table_name"

copy table

CREATE TABLE copy_of_table AS SELECT * FROM existing_table_name;

copy only table structure

CREATE TABLE copy_of_table AS SELECT * FROM existing_table_name WHERE 1 > 2;

Create new database user

CREATE USER 'user'@'hostname' IDENTIFIED BY 'PassWord';

To give remote access

GRANT ALL ON database_name.* to 'database_username'@'10.24.96.%' IDENTIFIED BY 'database_password';

CRUD SQL

SELECT * FROM users ORDER BY id DESC;

DELETE FROM users WHERE id = 3;

INSERT INTO users (id, name, age, city, added_at, updated_at) VALUES (NULL, 'sonam gupta', 18, 'gorakhpur', NOW(), NOW());

UPDATE users SET name = 'Sonam Gupta', age = 20, city = 'Gorakhpur', updated_at = NOW() WHERE id = 5;

Ref Links:

Git Ftp

NOTE: Run all commands from your projects root directory

#onetime
sudo apt-get install git-ftp

#onetime NOTE: PLEASE CHANGE WITH YOUR FTP SERVER URL
git config git-ftp.url "ftpupload.net"

#onetime NOTE: PLEASE CHANGE WITH YOUR FTP USERNAME
git config git-ftp.user "ftp-username"

#onetime NOTE: PLEASE CHANGE WITH YOUR FTP PASSWORD
git config git-ftp.password "ftp-password"

#onetime
git config git-ftp.syncroot .

#onetime
git ftp init --remote-root htdocs

git ftp push --remote-root htdocs

if you want to ignore files then create .git-ftp-ignore and add entries in this file

Ref:

https://www.codegrepper.com/code-examples/shell/git+ftp+empty+string+is+not+a+valid+pathspec.+please+use+.+instead+if+you+meant+to+match+all+paths

https://www.zyxware.com/articles/4192/how-to-deploy-files-from-a-git-repository-via-ftp

https://github.com/git-ftp/git-ftp

https://zoomadmin.com/HowToInstall/UbuntuPackage/git-ftp

https://github.com/git-ftp/git-ftp/blob/master/INSTALL.md#debian-ubuntu-and-others-using-apt

https://git-ftp.github.io/

https://github.com/git-ftp/git-ftp/blob/master/man/git-ftp.1.md

Install LEMP on WSL

To install Ubuntu Linux on windows follow instructions from following site

https://ubuntu.com/wsl

Open PowerShell as Administrator

wsl --list --verbose

If you see error then run following command

dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

Now enable WSL from Windows Features

Restart PC

Restart-Computer

Install Ubuntu from Microsoft Store

Once you install it will show launch option

Click on Launch or search Ubuntu on windows search

You will be prompted to add new user which will be default user of Ubuntu

Once successfully installed you can open powershell and check installed WSL on your system


To update wsl from version 1 to version 2 (Optional)
You need to run following command

wsl --set-default-version 2

If you get issue you can upgrade kernal component by download and installing update msi

https://docs.microsoft.com/en-us/windows/wsl/install-win10#step-4—download-the-linux-kernel-update-package

Once you update wsl kernal
Run following command again

Now update Ubuntu from version 1 to 2

If you get error do enable to Virtual Machine Platform from Windows Features

Now Restart PC

Restart-Computer

If you still get the error then do enable virtualization from BIOS setting


Ubuntu path on windows explorer

\\wsl$\Ubuntu

Update and Upgrade Kernal

sudo apt-get update
sudo apt-get upgrade

Install Nginx Web Server

sudo add-apt-repository ppa:nginx/stable
sudo apt-get update
sudo apt-get install -y nginx
sudo service nginx start
sudo service nginx status
sudo service nginx status

Install PHP and its services

sudo add-apt-repository ppa:ondrej/php
sudo apt-cache show php
sudo apt-get install php7.4-cli php7.4-fpm php7.4-curl php7.4-gd php7.4-mysql php7.4-mbstring zip unzip
php --version
php -r "echo 'Hello World' . PHP_EOL;"
php -S localhost:1234
sudo service php7.4-fpm start
sudo vim /etc/php/7.4/fpm/pool.d/www.conf

Find

listen =  127.0.0.1:9000

Replace

listen= /run/php/php7.4-fpm.sock
sudo vim /etc/nginx/sites-available/default

Find

index index.html index.htm index.nginx-debian.html;

Replace

index index.php index.html index.htm index.nginx-debian.html;

Find

#location ~ \.php$ {
# include snippets/fastcgi-php.conf;
#
# # With php-fpm (or other unix sockets):
# fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
# # With php-cgi (or other tcp sockets):
# fastcgi_pass 127.0.0.1:9000;
#}

Replace

location ~ \.php$
{
include snippets/fastcgi-php.conf;
#
# # With php-fpm (or other unix sockets):
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
# # With php-cgi (or other tcp sockets):
# fastcgi_pass 127.0.0.1:9000;
}

Restart Services

sudo service nginx reload
sudo service php7.4-fpm restart

Create index file in nginx’s default root directory

sudo touch /var/www/html/index.php
sudo vim /var/www/html/index.php

<?php
phpinfo();

Install MySQL server

sudo apt install mysql-server
sudo mysql_secure_installation

Create new user to access mysql from php/python or any other scripting language

if you face issue while connecting to database via php then run following commands by creating new user

CREATE USER 'phpuser'@'localhost' IDENTIFIED BY '%TGBbgt5';
GRANT ALL PRIVILEGES ON *.* TO 'phpuser'@'localhost';
FLUSH PRIVILEGES;

Ref: How to install Nginx + php + MySQL on WSL Windows 10 -H2S Media (how2shout.com)

PWA cheat sheet

index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="theme-color" content="#009578">
        <title>PWA</title>
        <link rel="stylesheet" href="src/master.css">
        <link rel="manifest" href="manifest.json">
        <link rel="apple-touch-icon" href="images/logo_2.jpg">
    </head>
    <body>
        <h3>Progressive Web App</h3>
        <script src="src/index.js"></script>
        <h4>Addition</h4>

    <label for="num1">Enter 1st Number:</label><br>
    <input type="text" id="num1" name="num1"><br>
    <br>

    <label for="num2">Enter 2nd Number:</label><br>
    <input type="text" id="num2" name="num2"><br><br>

    <button type="button" name="button" onclick="addition()">Add</button>

    <div>
        <h4>Result: <span id="res"> </span></h4>
    </div>

    <script>
        function addition() {
            var x = parseInt(document.getElementById("num1").value);
            var y = parseInt(document.getElementById("num2").value);

            var z = x + y;

            document.getElementById("res").innerHTML = z;
        }
    </script>

    </body>
</html>

manifest.json

{
    "name": "PWA demo",
    "short_name": "PWA",
    "start_url": ".",
    "background_color": "#6dcdb1",
    "theme_color": "#009578",
    "display": "standalone",
    "icons": [
        {
            "src": "images/logo_2.jpg",
            "sizes": "512x512",
            "type": "image/jpg"
        },
        {
            "src": "images/logo_1.png",
            "sizes": "512x512",
            "type": "image/png"
        }
    ]
}

sw.js

self.addEventListener("install", e => {
    // console.log("Install decode!");
    e.waitUntil(
        caches.open("static").then(cache => {
            return cache.addAll(["./", "./src/master.css", "./images/logo_2.jpg"]);
        })
    );
});


self.addEventListener("fetch", e => {
    // console.log(`Intercepting fetch request for: ${e.request.url}`);
    e.respondWith(
        caches.match(e.request).then(response => {
            return response || fetch(e.request);
        })
    );
});

src/index.js

if ("serviceWorker" in navigator) {
    navigator.serviceWorker.register("sw.js").then(registration => {
        console.log("SW Registered!");
        console.log(registration);
    }).catch(error => {
        console.log("SW Registration failed!");
        console.log(error);
    })
}

src/master.css

body {
    background: #eeeeee;
}

web socket chat app

chat_server.js

const express = require('express');
const http = require('http');
const WebSocket = require('ws');

const port = 8989;
const server = http.createServer(express);
const wss = new WebSocket.Server({ server })

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(data) {
    wss.clients.forEach(function each(client) {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(data);
      }
    })
  })
})

server.listen(port, function() {
  console.log(`Server is listening on ${port}!`)
})

index.html

<center><h1>WS Chat App</h1></center>
<pre id="messages" style="height: 400px; overflow: scroll"></pre>
<input type="text" id="messageBox" placeholder="Type your message here" style="display: block; width: 100%; margin-bottom: 10px; padding: 10px;" onkeyup="validateInput(event)"/>
<button id="send" title="Send Message!" style="width: 100%; height: 30px;">Send Message</button>

<script>
  (function() {
    const sendBtn = document.querySelector('#send');
    const messages = document.querySelector('#messages');
    const messageBox = document.querySelector('#messageBox');

    let ws;

    function showMessage(message) {
      if (message instanceof Blob) {
        reader = new FileReader();

        reader.onload = () => {
        //   console.log("Result: " + reader.result);
          messages.textContent += `\n\n${reader.result}`;
        };

        reader.readAsText(message);
      } else {
        console.log("Result: " + message);
        messages.textContent += `\n\n${message}`;
      }

      messages.scrollTop = messages.scrollHeight;
      messageBox.value = "";
    }

    function init() {
      if (ws) {
        ws.onerror = ws.onopen = ws.onclose = null;
        ws.close();
      }

      ws = new WebSocket('ws://localhost:8989');
      ws.onopen = () => {
        console.log('Connection opened!');
      }
      ws.onmessage = ({ data }) => showMessage(data);
      ws.onclose = function() {
        ws = null;
      }
    }

	
    sendBtn.onclick = function() {
      if (!ws) {
        showMessage("No WebSocket connection :(");
        return ;
      }

      ws.send(messageBox.value);
      showMessage(messageBox.value);
    }
	
	
	messageBox.onkeyup = function() {
		if(event.keyCode  == 13) {
			if (!ws) {
				showMessage("No WebSocket connection :(");
				return ;
			}

			ws.send(messageBox.value);
			showMessage(messageBox.value);
		}
    }

    init();
  })();
</script>

Angular Cheat Sheet

https://angular.io/guide/setup-local

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { AddComponent } from './add/add.component';
import { HomeComponent } from './home/home.component';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { HttpClientModule } from '@angular/common/http'

@NgModule({
  declarations: [
    AppComponent,
    AddComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app-routing.module.ts

if app-routing.module.ts is not present then run this in root folder
ng generate module app-routing –flat –module=app

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AddComponent } from './add/add.component';

const routes: Routes = [
  { path: 'add', component: AddComponent },
  { path: 'add/:num1/:num2', component: AddComponent },
  // { path: 'sub', component: SubComponent },
  // { path: 'mul', component: MulComponent },
  // { path: 'div', component: DivComponent },
  { path: '**', component: HomeComponent },
];

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    RouterModule.forRoot(routes)
  ],
  exports: [
    RouterModule
  ]
})
export class AppRoutingModule { }

app.component.html

<a routerLink="/"  routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">Home</a> |
<a routerLink="/add"  routerLinkActive="active">Add</a>
<router-outlet></router-outlet>

app.component.css

.active {
  background-color: beige;
}

home.component.ts

ng g c home

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms'
import { HomeService } from './home.service'

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  fruits = ["Orange", "Mango", "Banana", "Apple"];

  num1: number = 0;
  square: number = 0;

  form = new FormGroup({
    num1: new FormControl(),
    num2: new FormControl()
  });
  formResult: any;

  userRecords: any;

  constructor(private service: HomeService) { }

  ngOnInit() {
  }

  getSqr() {
    var x = this.num1;
    this.square = x * x;
  }

  addNum() {
    let x = parseInt(this.form.value.num1);
    let y = parseInt(this.form.value.num2);
    this.formResult = x + y;
  }

  getUsers() {
    this.service.getData().subscribe((response) => {
      console.log(response);
      this.userRecords = response;
    })
  }

}

home.component.html

<p>home works!</p>
{{ fruits }}

<div *ngFor="let fruit of fruits">
  {{fruit}}
</div>


<input type="text" (keyup)="getSqr()" [(ngModel)]="num1"/>
<div>
  Square of {{num1}} is {{square}}
</div>


<form [formGroup]="form" (submit)="addNum()">
  <input type="text" formControlName="num1"/>
  <input type="text" formControlName="num2"/>
  {{ form.value | json }}
  <div>
    Result: {{ formResult }}
  </div>
  <input type="submit" value="Add"/>
</form>


<button (click)="getUsers()">Get Data from Json Placeholder</button>
<div>
  {{userRecords}}
  <pre>
    {{userRecords | json}}
  </pre>
</div>

home.service.ts

cd home
ng g s home

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class HomeService {

  constructor(private http: HttpClient) { }

  getData() {
    let url = "https://jsonplaceholder.typicode.com/users";
    return this.http.get(url);
  }
}

add.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.css']
})
export class AddComponent implements OnInit {

  number: number;
  param1: number;
  param2: number;

  constructor(private route: ActivatedRoute, private router: Router) {
    console.log(this.route.snapshot.url)
    console.log(this.route.snapshot.params)
    this.number = parseInt(this.route.snapshot.queryParamMap.get('id'))
    this.param1 = parseInt(this.route.snapshot.params.num1);
    this.param2 = parseInt(this.route.snapshot.params.num2);
  }

  ngOnInit() {
    console.log(this.number)
    console.log(this.param1)
    console.log(this.param2)

    // setTimeout(() => {
    //   this.router.navigate(['home']);
    // }, 3000)
  }

}
my-app\src\app\interceptor\httpconfig.interceptor.ts
import { Injectable } from '@angular/core';
import {
    HttpInterceptor,
    HttpRequest,
    HttpResponse,
    HttpHandler,
    HttpEvent,
    HttpErrorResponse
} from '@angular/common/http';

import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

@Injectable()
export class HttpConfigInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const token: any = localStorage.getItem('token');
        // const token: string = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1X25hbWUiOiJhZG1pbiIsInB3ZCI6IkBkbWluIiwiaWF0IjoxNjEyNjM2OTc5fQ.ehlxu7z_1HSW4bPK902nLOAZOpHtutfkJ43lCxQnL68`;
        if (token) {
            request = request.clone({ headers: request.headers.set('Authorization', 'Bearer ' + token) });
        }

        if (!request.headers.has('Content-Type')) {
            request = request.clone({ headers: request.headers.set('Content-Type', 'application/json') });
        }

        request = request.clone({ headers: request.headers.set('Accept', 'application/json') });

        return next.handle(request).pipe(
            map((event: HttpEvent<any>) => {
                if (event instanceof HttpResponse) {
                    console.log('event--->>>', event);
                }
                return event;
            }));
    }
}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { RouterModule } from '@angular/router';

import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'
import { HttpConfigInterceptor } from './interceptor/httpconfig.interceptor';


@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    HttpClientModule
  ],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: HttpConfigInterceptor, multi: true }
  ],
  bootstrap: [AppComponent]

})
export class AppModule { }

Mongoose Express CRUD

const mongoose = require("mongoose");
const conn_str = "mongodb://localhost:27017/tcet"
mongoose.connect(conn_str, { useNewUrlParser: true , useUnifiedTopology: true})
	.then( () => console.log("Connected successfully...") )
	.catch( (err) => console.log(err) );

const userSchema = new mongoose.Schema({
	name: String,
	age: Number,
	city: String,
	state: String
});

const user = new mongoose.model("user", userSchema);

/** Express Mongoose Integration **/

const express = require("express");
const app = express();

app.route("/user")
.get(async (req, res) => {
	let data = await user.find();
	res.send(data);
})
.post(async (req, res) => {
	req_data = req.query;
	let obj = new user(req.query)
	let result = await obj.save();
	res.send(result);
})
.put(async (req, res) => {
	req_data = req.query;
	let result = await user.updateOne({_id: req.query.id}, {$set : {city: req.query.city}})
	res.send(result);
})
.delete(async (req, res) => {
	let result = await user.deleteOne({_id: req.query.id})
	res.send(result);
})

app.listen(8080, () => {
	console.log("listening 8080...");
});

Connect to MongoDB Atlas Cluster

Whitelist your ip / or allow from all 0.0.0.0/0

Get Your Current IP Address from google > what is my ip

Atlas > Security > Network Access > ADD IP ADDRESS

First get the connection string or URI from Atlas

Atlas > Deployment > Databases > Connect > Connect your application > Driver Node.js > Version 2.2.12 or later
const port = 8080;
const mongoose = require("mongoose");
const uri ="get_uri_from_atlas"
mongoose.connect(uri, { useNewUrlParser: true , useUnifiedTopology: true})
	.then( () => console.log("Connected successfully...") )
	.catch( (err) => console.log(err) );

const userSchema = new mongoose.Schema({
	name: String,
	age: Number,
	city: String
});

const user = new mongoose.model("users", userSchema);

/** Express Mongoose Integration **/

const express = require("express");
const app = express();

app.route("/user")
.get(async (req, res) => {
	let data = await user.find();
	res.send(data);
})
.post(async (req, res) => {
	req_data = req.query;
	let obj = new user(req.query)
	let result = await obj.save();
	res.send(result);
})
.put(async (req, res) => {
	req_data = req.query;
	let result = await user.updateOne({_id: req.query.id}, {$set : {city: req.query.city}})
	res.send(result);
})
.delete(async (req, res) => {
	let result = await user.deleteOne({_id: req.query.id})
	res.send(result);
})

app.listen(process.env.PORT || port, () => {
	console.log("listening 8080...");
});