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.send("Home Page");
});

app.get("/student", (req, res) => {
  data = { result: "Student GET Request" };
  res.send(data);
});

app.post("/student", (req, res) => {
  data = { result: "Student post Request" };
  res.send(data);
});

app.put("/student", (req, res) => {
  data = { result: "Student put Request" };
  res.send(data);
});

app.delete("/student", (req, res) => {
  data = { result: "Student delete Request" };
  res.send(data);
});

app
  .route("/teacher")
  .get((req, res) => {
    data = { result: "Teacher get Request" };
    res.send(data);
  })
  .post((req, res) => {
    data = { result: "Teacher post Request" };
    res.send(data);
  })
  .put((req, res) => {
    data = { result: "Teacher put Request" };
    res.send(data);
  })
  .delete((req, res) => {
    data = { result: "Teacher delete Request" };
    res.send(data);
  });


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

RUN COMMAND

#if file is index.js then you can simply run using . instead of filename
node .
node app.js

#install nodemon
npm i nodemon
OR
npm i -g nodemon

nodemon .
nodemon app.js

OR
 
./node_modules/nodemon/bin/nodemon.js .
./node_modules/nodemon/bin/nodemon.js app.js

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.send("student listing");
  })

  .post((req, res) => {
    res.send("student post");
  })

  .put((req, res) => {
    res.send("student put");
  })

  .delete((req, res) => {
    res.send("student delete");
  });

module.exports = router;

teacher.js

const express = require("express");
const router = express.Router();
router
  .route("/")
  .get((req, res) => {
    res.send("teachers listing");
  })
  .post((req, res) => {
    res.send("teachers post");
  })
  .put((req, res) => {
    res.send("teachers put");
  })
  .delete((req, res) => {
    res.send("teachers delete");
  });

module.exports = router;

EXPRESS READ DATA

index.js

const express = require("express");
const app = express();
app.use(express.json());

app
  .route("/")
  .get((req, res) => {
    data = req.query;
    res.send(data);
  })
  .post((req, res) => {
    data = req.body;
    res.send(data);
  })
  .put((req, res) => {
    data = req.body;
    res.send(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.

Fetch Api

<table border=1>
	<thead>
		<th>Id</th>
		<th>Name</th>
		<th>Email</th>
		<th>Aavatar</th>
	</thead>
	<tbody id="records">
		<tr>
			<td>sample </td>
			<td>sample</td>
			<td>sample</td>
			<td>sample</td>
		</tr>
	</tbody>

</table>
<img id="image" />
<script>
	url = "https://reqres.in/api/users?page=1";

	fetch(url)
	.then(res => res.json())
	.then(result => {
		console.table(result.data);
		console.log(result.data[0]['avatar'])
		document.getElementById("image").src = result.data[0]['avatar'];
		records = result.data;
		output = '';
		for(i = 0;i<records.length; i++){
			output += `<tr>`
			output += `<td>${records[i]['id']} </td>`
			output += `<td>${records[i]['first_name']} ${records[i]['last_name']}</td>`
			output += `<td>${records[i]['email']}</td>`
			output += `<td><img id="image" src="${records[i]['avatar']}" /></td>`
			output += `</tr>`
			console.log(records[i]['id'])
		}
	document.getElementById("records").innerHTML = output;
	
	})
	
</script>

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

Fetch Data From Google Sheet

let offset = 'A2';
let limit = 'Z999';
const sheetid = "<sheetid>"; 

const apikey = "<api key>"; 

const sheetname = "Sheet1";
const url = `https://sheets.googleapis.com/v4/spreadsheets/${sheetid}/values/${sheetname}!${offset}:${limit}?key=${apikey}`;

var sheet_data = [];

fetch(url).then(data => data.json()).then(data => { 
	sheet_data = data.values;
	console.table(sheet_data);
});

Sample Google Sheet Data

To get sheet id
Click on share then copy link

Create API Key

Final Output in HTML

Assignment

===========================================================================
Week 1 Assignment
===========================================================================

  1. WAP to read radius of circle and calculate Area and Circumference
  2. WAP to read 3 numbers and find their mean
  3. WAP to read 2 numbers and find Sum of their last digit
  4. WAP to read 4 digit number and sum of its digits
  5. WAP to read radius of Sphere and find its Volume
  6. WAP to read 3 digit number and sum of its digit
  7. WAP to read 4 digit number and find reverse of that number
  8. WAP to read temperature in degree Celsius and convert it into Fahrenheit
  9. WAP to read value in inches and print it in feet and inches
  10. WAP to read marks of 5 subjects and print total and percentage
  11. Create radio button
    red blue yellow green
    on change of radio button change background color of body
  12. Create 2 select box and move items from left to right and vice versa
  13. Create 3 select box country state city
  • on change of country load states
  • on change of state load cities

Programs on If Statement

SWITCH Statement

===========================================================================
Week 2 Assignment
===========================================================================

Loops Programs

Arrays Programs (One Dimensional)

Arrays Programs (Multi Dimensional)

JSON

  1. Create JSON Object with following information
    Roll Number, Name, Age, Sex
    EmpNo, Name, Job, Sal
    Name, Wages, WorkingDays
  2. WAP to create array of 5 json objects worker and display average payment
    object parameter: name,wages,working_days
  3. WAP to create array of 5 json objects student and print all student records who has greater than average marks
    roll_no, name, marks

AJAX (fetch API)

  1. WAS to make AJAX call for following operations
    1. Input a number in text box and get square of that number from php script
    2. Input 2 numbers in text box and get addition of two numbers from php script
    3. Input radius in text box and find area and circumference of circle from php script
    4. Input length and breadth in text box and find area of rectangle from php script
    5. Input a number in text box and find factorial of number from php script
  2. WAP to print users data in html table by making ajax call to
    • https://jsonplaceholder.typicode.com/users
    • https://reqres.in/api/users (should have column to display thumbnail of user avatar)

===========================================================================
Week 3 Assignment
===========================================================================

  1. Design a class Rectangle
    • data members:
      1.  length
      2. breadth
    • member function / method: 
      1. setDimension()
      2. area()
      3. perimeter()
  2. Design a class Worker
    • data members:
      1. wages
      2. wdays
    • member function / method:
      1. setData()
      2. payment()
  3. Design a class Box
    • data members:
      1. length
      2. breadth
      3. height
    • member functions / methods:
      1. setDimension()
      2. volume()
  4. Design a class Rectangle
    • data members:
      1. length
      2. breadth
    • member functions / methods:
      1. setDimension()
      2. area()
      3. perimeter()
  5. Design a class Box
    • data members:
      1. length
      2. breadth
      3. height
    • member functions / methods:
      1. volume()
  6. Design a class Account
    • data members:
      1. account_number
      2. balance
    • member functions / methods:
      1. deposit()
      2. withdraw()
      3. showBalance()
  7. Design a class Set
    • data members:
      1. 3 numbers
    • member functions / methods:
      1. SUM()
      2. MEAN()
      3. MAX()
      4. MIN()
  8. Design a class Student
    • data members:
      1. roll_number
      2. name
    • member functions / methods:
      1. setData()
      2. getData()
  9. Design a class Account
    • data members:
      1. account_number
      2. balance
      3. interest_rate
        NOTE: interest_rate must be shared by all objects and its default value 10.25
    • member function:
      1. interest(no_of_years)
  10. Design a class Student
    • data members:
      1. roll_number
      2. name
    • member functions / methods:
      1. setData()
      2. getData()
        NOTE: roll_number must be automatically generated.It also keep track of total number of Students.
  11. Design a class Student
    • data members:
      1. roll_number
      2. name
    • member functions / methods:
      1. getData()
      2. showData()
        Create Array of 5 Student objects
  12. Create array of Student Objects
    • data members:
      1. roll_no
      2. name
      3. college
    • member functions / methods:
      1. readData()
      2. showData()
  13. Create a class RBI
    • data members:
      1. account_number
      2. balance
    • member functions / methods:
      1. deposit(int amt)
      2. withdraw(int amt)
      3. showBalance()

Fun with JS CSS and HTML

  1. Create radio button red blue yellow green on change of radio button change background color of body
  2. Create 2 select box and move items from left to right and vice versa
  3. Create 3 select box country state city a) on change of country load states b) on change of state load cities
    NOTE: Use AJAX call and fetch country states and cities from mysql database
  4. Create tic-tac-toe game.
    1. single player with computer
    2. multiplayer with manual event

OOPS

  1. Design a class Rectangle
    data members
    length
    breadth
    member functions/methods
    setDimension()
    area()
    perimeter()

  2. Design a class Worker
    data members
    wages
    wdays
    member function / method
    setData()
    payment()

  3. Design a class Box
    data members
    length
    breadth
    height
    member functions / methods
    setDimension()
    volume()

  4. Design a class Rectangle (only for Java / C++)
    data members
    length
    breadth
    member functions / methods
    setDimension()
    area()
    perimeter()
    It must overload setDimension() method twice:
    1. by passing 1 argument
    2. by passing 2 arguments

  5. Design a class Box (only for Java / C++)
    data members
    length
    breadth
    height
    member functions / methods
    volume()
    It must contain 3 constructors
    1. 1 parameter
    2. 2 parameter
    3. 3 paramter
  6. Design a class Account
    data members
    balance
    member functions / methods
    deposit(amt)
    withdraw(amt)
    showBalance()

  7. Design a class Set
    data members
    3 numbers
    member functions / methods
    SUM()
    MEAN()
    MAX()
    MIN()

  8. Design a class Student
    data members
    roll_number
    name
    member functions / methods
    setData()
    getData()

  9. Design a class Account
    data members
    balance
    interest_rate
    interest_rate must be shared by all objects (static modifier) and its default value 10.25
    interest(no_of_years)

  10. Design a class Student
    data members
    roll_number
    name
    member functions / methods
    setData()
    getData()

  11. Design a class Account
    account_number
    balance
    interest_rate
    member functions / methods
    interest(no_of_years)

  12. Design a class Student
    data members
    roll_number
    name
    member function / methods
    getData()
    roll_number must be automatically generated.It also keep track of total number of Students.

  13. Design a package MyCircle and MyRectangle (Only for Java)
    radius
    length
    breadth
    member functions / methods:
    area()
    circumference()
    perimeter()

  14. Design a class Student
    data members
    roll_number
    name
    member functions / methods
    getData()
    showData()
    Create 5 objects of Student using Array

  15. Design a class Student and List ClassRoom
    add list of Students in ClassRoom
    display List

  16. Design a class Account and List Bank
    add list of Account in Bank
    display List

  17. Create array of Student Objects
    data members
    roll_no
    name
    college
    member functions / methods
    readData()
    showData()

  18. Create a class RBI (Only for Java)
    data members
    balance
    member functions
    RBI()
    deposit(int amt)
    withdraw(int amt)
    showBalance()

Arrays Programs (Multi Dimensional)

  1. WAP to read a matrix of size 3 X 5 and find their SUM
  2. WAP to read a matrix of size 3 X 5 and find sum of each ROW
  3. WAP to read a matrix of size 3 X 3 and check if it is NULL or NOT
  4. WAP to read a matrix of size 3 X 5 and count all EVEN and ODD numbers
  5. WAP to read matrix of size 3 X 3 and check if it is UNIT Matrix or NOT
  6. WAP to read 2 matrix of size 3 X 3 and find their Addition
  7. WAP to read 2 matrix of size 3 X 3 and find their Product
  8. WAP to read matrix of size 3 X 3 and find its Transpose
  9. WAP to read matrix of size 3 X 3 and find its Transpose without using second matrix
  10. WAP to read matrix of size 3 X 3 and find its Upper Triangular Matrix
  11. WAP to read matrix of size 3 X 3 and find its Lower Triangular Matrix
  12. WAP to read matrix of size 3 X 3 and check if sum of its diagonal is same or not
  13. WAP to read matrix of size 3 X 3 and check if sum of its middle row is same as sum of its middle column
  14. WAP to create TIC-TAC-TOE by showing number and take 9 inputs from 2 users.
    1 2 3
    4 5 6
    7 8 9

    X O X
    O X O
    O O X

    PLAYER 1 WIN
    O X O
    X O X
    O X O

    PLAYER 2 WIN

Arrays Programs (One Dimensional)

  1. WAP to read an array of 10 numbers and find their sum
  2. WAP to read temperature days of Week and find their Mean
  3. WAP to read an array of 10 numbers and find greatest of them
  4. WAP to read an array of 10 numbers and count all EVEN and ODD numbers
  5. WAP to rad an array of 10 numbers and find sum, mean, min, max
  6. WAP to read an array of 10 numbers and search a number in it
  7. WAP to read an array of 10 numbers and sort it in ascending order
  8. WAP to read an array of 10 numbers and sort it in descending order
  9. WAP to insert a number at given position in an array (optional)
  10. WAP to remove a number from given position from an array (optional)
  11. WAP to arrange all even numbers at top and all odd numbers at bottom of an array (optional)

FUNCTIONS

  1. WAF repeat to display a char specified no of times.
  2. WAF intrest to calculate simple intrest.
  3. WAF to return Volume of Sphere
  4. WAF to return mean of 3 numbers
  5. WAF to return greatest of 2 numbers
  6. WAF to return Factorial of given Number
  7. WAF to return Sum of Given Number.
  8. WAF to return Greatest of 3 numbers.
  9. WAF to print all numbers from 1 to given numbers
  10. WAF to repeat a given char given number of timest.
    e.g. repeat(‘#’, 25)
  11. Design a recursive function factorial to return factorial of given number.
  12. Design a recursive function intrest to return compound intrest.
  13. Design a recursive function SOD to return sum of digit of given number.
  14. WAF to return sum of number which is passed in a Array.
  15. WAF to return Mean of numbers which is passed in a Array.
  16. WAF to return Greatest number which is passed in a Array.

SWITCH Statement

  1. WAP to read a single digit number and print that number in words.
  2. WAP to read month in digits print it in words.
  3. WAP to read a single number and print all numbers from 1 to that number in words.
  4. WAP to read a color code (char value) and print appropriate color.
    (e.g. R – Red, G- Green, B-Blue and other char – Black)
  5. WAP to read 2 numbers and a Operator sign and perform the operation according to operator.
    (e.g.
    i/p:
    5
    7
    +

5+7=12
)

  • WAP to count total number of vowels in a string by using a switch statement
  • WAP to count total number of vowels of each type