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) {
      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...");
});

mongoose cheat sheet

Insert

console.log("mongo db connection");

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( (error) => console.log(error));
	
//schema defining for collection
const teacherSchema = new mongoose.Schema({
	name: {
		type: String,
		required: true
	},
	age: Number,
	city: String
})

// create collection
const Teacher = new mongoose.model("Teacher", teacherSchema);
console.log(Teacher);
	
/*insertOne
const t1 = new Teacher({name: "Shailesh", age: 32, city: "Nagpur"});
console.log(t1.save());


//insertOne
const insertOne = async () => {
	try {
		const t2 = new Teacher({name: "Amy", age: 32, city: "Nagpur"});
		const result = await t2.save();
		console.log(result);
	} catch(e) {
		console.log(e);
	}
};

insertOne();


//insertMany
const insertMany = async () => {
	try {
		const t1 = new Teacher({name: "Amy1", age: 32, city: "Nagpur"});
		const t2 = new Teacher({name: "Amy2", age: 32, city: "Nagpur"});
		const t3 = new Teacher({name: "Amy3", age: 32, city: "Nagpur"});
		const result = await Teacher.insertMany([t1,t2,t3]);
		console.log(result);
	} catch(e) {
		console.log(e);
	}
};

insertMany();
*/

Connection Module

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( (error) => console.log(error));
	
//schema defining for collection
const teacherSchema = new mongoose.Schema({
	name: {
		type: String,
		required: true
	},
	age: Number,
	city: String
})

// create collection
const Teacher = new mongoose.model("Teacher", teacherSchema);

exports.Teacher = Teacher;

Read

var teacher = require("./teacher");
const Teacher = teacher.Teacher;

/*
const t1 = new Teacher({name: "Penny", age: 25, city: "Nagpur"});
console.log(t1.save());
*/

const getData = async () => {
const data = await Teacher.find({name: /l/i}).select({_id: 0, __v: 0}).limit(2).sort({name: -1});
	console.log(data);
}

getData();

Update

var teacher = require("./teacher");
const Teacher = teacher.Teacher;

/*
const updateOne = async (oname, nname) => {
	try {
		var res = await Teacher.updateOne({name: oname}, {
			$set : { name : nname }
		});
		console.log(res);
	} catch (e) {
		console.log(e);
	}
}

updateOne("Howa", "Kuwa.....");

const updateMany = async (city) => {
	try {
		var res = await Teacher.updateMany({age: {$lt: 30}}, {
			$set : { city : city }
		});
		console.log(res);
	} catch (e) {
		console.log(e);
	}
}

updateMany("Mumbai");

*/

Delete

var teacher = require("./teacher");
const Teacher = teacher.Teacher;

/*
const deleteMany = async (where) => {
	try {
		var res = await Teacher.deleteMany(where);
		console.log(res);
	} catch(error) {
		console.log(error);
	}
}

deleteMany({age : {$in: [25, 37]}});
*/

NodeJS Cheat Sheet

NODE CUSTOM MODULE

index.js

var mymath = require("./mymodule")

console.log(mymath.add(5,6));
console.log(mymath.sub(5,6));
console.log(mymath.mul(5,6));
console.log(mymath.div(5,6));
console.log(mymath.mod(5,6));

cobj = new mymath.MyCircle(5);
cobj.area();

mymodule.js

exports.add = (x, y) => x + y;
exports.sub = (x, y) => x – y;
exports.mul = (x, y) => x * y;
exports.div = (x, y) => x / y;
exports.mod = (x, y) => x % y;

exports.MyCircle = class {

constructor(r) {
    this.radius = r;
    console.log("Hello I am My Circle Constructor...");
}

area() {
    let area = Math.PI * this.radius * this.radius;
    console.log(`Area: ${area.toFixed(2)}`);
}
}

NODE http MODULE

index.js

var http = require(“http”)

http.createServer((req, res) => {
// res.writeHead(‘Content-Type’, ‘text/plain’);
// res.writeHead(‘Content-Type’, ‘application/json’);
res.writeHead(200, {‘Content-Type’ : ‘text/html’});
res.write("this is line 1….");

console.log(req.url);

if(req.url == "/") {
    res.write("Home req hit</br>")
} else 

if(req.url == "/teacher") {
    res.write("Teacher req hit</br>")
} else 

if(req.url == "/student") {
    res.write("Student req hit</br>")
} else 

{
    res.end("Page Not Found....");
}

res.end("hello world....");
}).listen(8989, () => {
console.log("listening at port 8989…")
});

EXPRESS ROUTING

index.js

var express = require(“express”)
var app = express();

app.get(“/”, (req, res) => {
// res.setHeader(‘Content-Type’, ‘text/plain’);
// res.setHeader(‘Content-Type’, ‘application/json’);
res.setHeader(‘Content-Type’, ‘text/html’);
res.send(“Home Page”);
})

app.get(“/student”, (req, res) => {
res.setHeader(‘Content-Type’, ‘application/json’);
data = { “result” : “Student GET Request”}
res.send(JSON.stringify(data))
})
app.post(“/student”, (req, res) => {
res.setHeader(‘Content-Type’, ‘application/json’);
data = { “result” : “Student post Request”}
res.send(JSON.stringify(data))
})
app.put(“/student”, (req, res) => {
res.setHeader(‘Content-Type’, ‘application/json’);
data = { “result” : “Student put Request”}
res.send(JSON.stringify(data))
})
app.delete(“/student”, (req, res) => {
res.setHeader(‘Content-Type’, ‘application/json’);
data = { “result” : “Student delete Request”}
res.send(JSON.stringify(data))
})

app.route(“/teacher”)
.get((req, res) => {
res.setHeader(‘Content-Type’, ‘application/json’);
data = { “result” : “Teacher get Request”}
res.send(JSON.stringify(data))
})
.post((req, res) => {
res.setHeader(‘Content-Type’, ‘application/json’);
data = { “result” : “Teacher post Request”}
res.send(JSON.stringify(data))
})
.put((req, res) => {
res.setHeader(‘Content-Type’, ‘application/json’);
data = { “result” : “Teacher put Request”}
res.send(JSON.stringify(data))
})
.delete((req, res) => {
res.setHeader(‘Content-Type’, ‘application/json’);
data = { “result” : “Teacher delete Request”}
res.send(JSON.stringify(data))
})

app.listen(8989, () => {
console.log(“Listening at port 8989”);
})

EXPRESS MODULAR ROUTING

index.js

var express = require(“express”);
var app = express();
var home = require(“./home”)
var student = require(“./student”)
var teacher = require(“./teacher”)

app.use(“/”, home);
app.use(“/student”, student);
app.use(“/teacher”, teacher);

app.use(function(req, res, next) {
res.status(404);
res.send(‘404: File Not Found’);
});

app.listen(8989, () => {
console.log(“Listening at port 8989”);
});

student.js

const express = require(“express”);
const router = express.Router();

router.route(“/”)
.get((req, res)=>{
res.setHeader(‘Content-Type’, ‘text/html’);
res.send(“student listing”);
})

.post((req, res)=>{
res.setHeader(‘Content-Type’, ‘text/html’);
res.send(“student post”);
})

.put((req, res)=>{
res.setHeader(‘Content-Type’, ‘text/html’);
res.send(“student put”);
})

.delete((req, res)=>{
res.setHeader(‘Content-Type’, ‘text/html’);
res.send(“student delete”);
})

module.exports = router

teacher.js

const express = require(“express”);
const router = express.Router();

router.route(‘/’)
.get((req, res)=>{
res.setHeader(‘Content-Type’, ‘text/html’);
res.send(“teachers listing”);
})

.post((req, res)=>{
res.setHeader(‘Content-Type’, ‘text/html’);
res.send(“teachers post”);
})

.put((req, res)=>{
res.setHeader(‘Content-Type’, ‘text/html’);
res.send(“teachers put”);
})

.delete((req, res)=>{
res.setHeader(‘Content-Type’, ‘text/html’);
res.send(“teachers delete”);
})

module.exports = router;

EXPRESS READ DATA

index.js

const express = require(“express”);
const app = express();

const bodyParser = require(‘body-parser’);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json())

app.route(“/”)
.get((req, res) => {
res.setHeader(‘Content-Type’, ‘application/json’);
data = req.query;
res.send(JSON.stringify(data));
})
.post((req, res) => {
res.setHeader(‘Content-Type’, ‘application/json’);
data = req.body;
res.send(JSON.stringify(data));
})
.put((req, res) => {
res.setHeader(‘Content-Type’, ‘application/json’);
data = req.body;
res.send(JSON.stringify(data));
})

app.listen(8989, () => {
console.log(“Listening at port 8989”);
});

Assignment: WA Web Service to read number from user and return square and cube of that number. Return data in JSON format.

Express File Upload

//get directory name
console.log(`Project Path: ${__dirname}`);

const express = require("express");
const fileUpload = require("express-fileupload");
const app = express();

//options / middleware
app.use(fileUpload());

app.post("/file_upload", (req, res) => {
	
	console.log(req.body);
	console.log(req.files);
	
	let file_to_upload = req.files.file_to_upload;
	
	//file_to_upload.mv(path,callbackfun);
	const upload_path = __dirname + '/uploads/' + file_to_upload.name;
	//file_to_upload.mv(upload_path);
	
	file_to_upload.mv(upload_path, (err) => {
		if(err) {
			res.status(500)
			res.send(err);
		}
		
		res.status(200)
		res.send("File Upload successfully...")
	})
	
});

app.listen(8989, () => {
	console.log("Listening at port 8989");
})

json webtoken

var jwt = require('jsonwebtoken');
var express = require("express");
var app = express();

username = "admin";
password = "@dmin";

app.use(express.json());

var cors = require('cors')
app.use(cors())

function errorHandler(req, res, next) {
    if (!req.headers.authorization) return res.status(401).send({message:"No token provided"});

    const token = req.headers.authorization.replace("Bearer ","");

    jwt.verify(token, 'shhhhh', function(err) {
        if (err){
            res.status(401).send({message: "unauthorized user"});
        } 
        res.send("jwt token is correct");
    });

    return res.status(500).json({ message: err.message });
}


app.route('/login')
.post((req, res)=>{
    if (username==req.body.username && password == req.body.password){
        var token = jwt.sign({ u_name: username}, 'shhhhh');
        res.send(token);
    }else{
        res.send("wrong creditionals");
    }
    
})

app.use(errorHandler)

app.route('/dashboard')
.get((req,res)=>{
    res.send("dashboard");
})

app.route('/employees')
.get((req,res)=>{
    res.send("emloypee page");
})

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

MongoDB Cheat Sheet

MongoDB is a source-available cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas.

to start server (mongod is mongo deamon)

mongod

to start shell

mongo
show dbs;
create/use database

Change database

use db_name;

show current database

db;

Collections are similar to table

show collections;
db.createCollection("students");

Drop collection/table

db.students.drop();

drop database

db.dropDatabase();

insertOne

db.students.insertOne({_id: 1, name: "shailesh"});

insertMany

db.students.insertMany([{_id: 2, name: "bagde"}, {_id: 3, name: "sheldon"}]);

count document

db.students.count();

select all documents/records

db.students.find();

select with projection

db.students.find({},{_id: 0});
db.students.find({},{name:0});

exists operator

db.students.find({age: {$exists: false}});

COMPARISON OPERATORS

in operator

db.students.find({_id: {$in: [2,3]}});

not equal operator

db.students.find({_id: {$ne: 2}});

equal operator

db.students.find({_id: {$eq: 2}});

less than $lt

less than equal $lte

greather than $gt

greater than equal $gte

LOGICAL OPERATORS

$and operator

db.students.find({$and : [{_id : {$gt:1}}, {_id: {$lt: 4}}]})

$or operator

db.students.find({$or : [{name : "bagde"}, {name: "shailesh"}]})

like case insensitive

db.students.find({name: /h/i})

exact match

db.students.find({name: /^BagDe$/i})

UPDATE

db.students.updateOne({_id: 1}, {$set : {age: 23}});
db.students.updateMany({age : {$exists: false}}, { $set : {age : 25}})
db.students.updateMany({}, {$set: {address: {city: "Mumbai", state: "MH"}}})
db.students.updateOne({_id: 4}, { $set : {address : {city: "Nagpur"}}});

Unset/Delete Fields

db.students.updateMany({}, {$unset : {city: ""}});

search within sub document

db.students.find({"address.city" : "Nagpur"}).pretty();

Delete Records

db.students.deleteOne({ $or : [{ age : {$lt : 25}}, {name : "sheldon"}] })

ORDER BY

db.students.find().sort({name: -1})

LIMIT

db.students.find().sort({name: -1}).limit(1)

MongoDB Assignment for Practice

var docs = [
{"name":"nehav ","contact_number":"9833910534","address":"mumbai","salary":30000,"employee_id":98821,"role":"manager"},
{"name":"mina ","contact_number":"9833910535","address":"thane","salary":32000,"employee_id":98823,"role":"sales"},
{"name":"pankaj ","contact_number":"9833910536","address":"bhopal","salary":40000,"employee_id":98824,"role":"hr"},
{"name":"mareena ","contact_number":"9833910537","address":"meerut","salary":45000,"employee_id":98825,"role":"support"},
{"name":"pooja","contact_number":"9833910538","address":"delhi","salary":50000,"employee_id":98826,"role":"developer"},
{"name":"namita","contact_number":"9833910539","address":"surat","salary":52000,"employee_id":98820,"role":"sales"},
{"name":"sneha ","contact_number":"9833910510","address":"baroda","salary":55000,"employee_id":98827,"role":"support"},
{"name":"anjali ","contact_number":"9833910511","address":"ahmedabad","salary":60000,"employee_id":98828,"role":"tester"},
{"name":"harsha ","contact_number":"9833910512","address":"mumbai","salary":20000,"employee_id":98829,"role":"operations"},
{"name":"varun ","contact_number":"9833910512","address":"mehsana","salary":56000,"employee_id":98831,"role":"tester"},
{"name":"preeti ","contact_number":"9833910513","address":"noida","salary":87000,"employee_id":98832,"role":"developer"},
{"name":"madhu","contact_number":"9833910525","address":"bangalore","salary":22000,"employee_id":98833,"role":"sales"}
];

db.createCollection("emps");
db.insertMany(docs);
db.emps.find();
  1. show employees in descending order – salary
  2. show all employees from Mumbai
  3. show all employees having salary more 50000
  4. show sum of salary from emps collection
  5. show all distinct address
  6. show names of employees having max salary
  7. show employees having 2nd max salary
  8. count employees from mumbai only
  9. show all employees whose names starts or ends with vowels
  10. show all employees whose names starts and ends with consonant

TCET Session Data

day 2:
javascript: addeventlisterner, fetchapi, validation
mongodb: crud on terminal
nodejs: core, custom module, http module
expressjs: routeing with get,post, put, delete methods
routing with route methods
read query params using res.query
read form data using res.body parser
read raw json using res.body parser
mongodb crud using nodejs (mongoose)

Day 1: JavaScript
Introduction
console.log()
console.error()
console.warning()
alert()
confirm()

variables, datatypes and scope
var x | let x | x

concatenation
template literals hello ${name}

Conditional Statement if..else

Loops for

String and String methods

Array and Array methods

Math methods

Functions

callback function

lambda expression/fatarrow function

Classes and Objects

Array of Objects

Inheritance

Interface

JSON

Array of JSON

AJAX using fetch API and json-placeholder dummy API

UI
read data from input box
put data in input box
put data in html

addEventListener

events (onclick, onkeyup, onkeydown, onkeypress, onfocus, onchange, onblur)

JavaScript Validation

Load data in table from API (Web Service: json-placeholder) using AJAX call (fetch API)

=====================================================================