0% found this document useful (0 votes)
14 views45 pages

FSD Lab Manual 1736308175

The document is a lab manual for a Full Stack Development course, detailing course objectives, a list of experiments, and expected outcomes. It includes various programming tasks using HTML, CSS, JavaScript, and React, aimed at teaching students about web development concepts such as higher order functions, class components, and hooks. The manual is prepared by Mr. S. Kishore Babu from the Department of AI & DS at Vasireddy Venkatadri Institute of Technology.

Uploaded by

bhargav0626
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views45 pages

FSD Lab Manual 1736308175

The document is a lab manual for a Full Stack Development course, detailing course objectives, a list of experiments, and expected outcomes. It includes various programming tasks using HTML, CSS, JavaScript, and React, aimed at teaching students about web development concepts such as higher order functions, class components, and hooks. The manual is prepared by Mr. S. Kishore Babu from the Department of AI & DS at Vasireddy Venkatadri Institute of Technology.

Uploaded by

bhargav0626
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

R20

Full Stack
Development
Lab Manual

Prepared by

Mr.S.Kishore Babu

Department of AI&DS

Vasireddy Venkatadri Institute of Technology Nambur(V), Peda


kakani(M), Guntur Dt.- 522508
Credits to :Ms Rajya Lakshmi
VASIREDDY VENKATADRI INSTITUTE OF TECHNOLOGY
(Autonomous) Nambur (V), Pedakakani (M), Guntur (Dt.), Andhra Pradesh – 522 508
DEPARTMENT OF CSE –INTERNET OF THINGS (IoT)
FRONT END APPLICATION DEVELOPMENT LAB
Course objectives:
At the end of the course the students will understand
1. Higher order functions
2. Class Components.
3. Functional Components.
4. Different types of Hooks.
5. React application with data base connectivity.

List of experiments
1. Try to recreate the following patterns using HTML and CSS only.

2. Implement Drag n Drop feature in HTML 5


3. Demonstrate Event bubbling with necessary examples.
4. Design a Calculator using Java script and relevant CSS.
5. Demonstrate Higher order functions with necessary examples – filter(), reduce() and
map()
6. Create a Class Component for Counter in React JS
7. Create a Class component for Changing the color of the text given in React JS
8. Class a Class Component for viewing an array of objects in a tabular form.
9. Display a digital clock in React JS.
10. Demonstrate useState Hook with the help sample text.
11. Demonstrate useContext Hook with necessary example.
12. Demonstrate useEffect Hook with necessary example.
13. Demonstrate consuming web API using fetch & axios (AXIOS API). Demonstrate with
the help of fake URL.
14. Design a BMI calculator using React JS based on the description given below: BMI is
a measurement of a person's leanness or corpulence based on their height and weight,
and is intended to quantify tissue mass. It is widely used as a general indicator of
whether a person has a healthy body weight for their height.
Formula: weight (kg) / [height (m)]2 (or) [weight (kg) / height (cm) / height (cm)] x
10,000 BMI table for adults: This is the World Health Organization's (WHO)
recommended body weight based on BMI values for adults. It is used for both men
and women, age 18 or older.

15. Display a selected set of images in tabular format using React JS.
16. Implement Upload & down load options on a given file.
17. Create a React application to view EMI calculator. A specific view is given below:
18. Design the following Hotel bill screen. User can select as many items as possible from
the dropdown box and is allowed to enter in the text field provided. Each transaction
must be added in the table given below along with the bill amount.

19. Demonstrate the procedure to create a schema in MongoDB.


20. Demonstrate CRUD operations using MongoDB

Course Outcomes: Upon successful completion of the course


CO1 Use Higher Order functions like filter(), reduce(), map()
CO2 Develop a react application using class components
CO3 Develop a react application using functional components
CO4 Develop a complete react application with data base connectivity
1. Aim: Try to recreate the following patterns using HTML and CSS only.

Program:
<!DOCTYPE html>
<html>
<head>
<style>
.container{
display: grid;
grid-template-columns: repeat(6,25px);
grid-template-rows: repeat(5,25px);
grid-gap: 2px;
width: 250px;
}
.items1{
background: orange;
}
.items2{
background: lightgreen;
}
.items3{
background: darkgreen;
}
</style>
<title>GridLayout</title>
</head>
<body>
<center>
<div class="container">
<div class="items1"></div>
<div class="items2"></div>
<div class="items3"></div>
<div class="items1"></div>
<div class="items2"></div>
<div class="items3"></div>

<div class="items2"></div>
<div class="items3"></div>
<div class="items1"></div>
<div class="items2"></div>
<div class="items3"></div>
<div class="items1"></div>

<div class="items3"></div>
<div class="items1"></div>
<div class="items2"></div>
<div class="items3"></div>
<div class="items1"></div>
<div class="items2"></div>

<div class="items1"></div>
<div class="items2"></div>
<div class="items3"></div>
<div class="items1"></div>
<div class="items2"></div>
<div class="items3"></div>

<div class="items2"></div>
<div class="items3"></div>
<div class="items1"></div>
<div class="items2"></div>
<div class="items3"></div>
<div class="items1"></div>
</div>
</center>
</body>
</html>

Output:
2. Aim: Implement Drag n Drop feature in HTML 5
Program:
<!DOCTYPE html>
<html>
<body>
<div width="100" height="1500" style="border: 200px solid black;
background-color: black;" ondragover="allowdrop(event)"
ondrop="drop(event)">
</div> <br><br>
<img src="D:\HTML\Logo.jpg" id="dragtarget" height="200px"
width="180px" ondragstart="drag(event)" draggable="true">
<script>
function drag(event){
event.dataTransfer.setData("text",event.target.id)
}
function allowdrop(event){
event.preventDefault()
}
function drop(event){
event.preventDefault()
var data = event.dataTransfer.getData("text")
event.target.appendChild(document.getElementById(data))
}
</script>
</body>
</html>

Output:
3. Aim: Demonstrate Event bubbling with necessary examples.
Program:
<!DOCTYPE html>
<html>
<head>
<style>
#grandparent{
width: 300px;
height: 300px;
background: black;
}
#parent{
width: 200px;
height: 200px;
background: blue;
}
#child{
width: 100px;
height: 100px;
background: yellow;
}
</style>
</head>
<body>
<div id="grandparent">
<div id="parent">
<div id="child">
</div>
</div>
</div>
<script>
let grandparent = document.getElementById("grandparent")
let parent = document.getElementById("parent")
let child = document.getElementById("child")
grandparent.addEventListener("click",function(){alert("grandparent")},{capture:false})
parent.addEventListener("click",function(){alert("parent")},{capture:false})
child.addEventListener("click",function(){alert("child")},{capture:false})
</script>
</body>
</html>

Output:
4. Aim: Design a Calculator using Java script and relevant CSS.
Program:
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
<style>
.calci{
width: 450px;
height: 620px;
margin-top: 90px;
background: teal;
}
.text{
height: 50px;
font-size: 15px;
font-weight: bold;
background: tan;
border-color: gray;
}
.button{
background-color: tan;
color: black;
padding: 16px 40px;
text-align: center;
font-size: 20px;
font-weight: bold;
}
.answer{
background: tan;
font-size: 30px;
text-align: center;
font-weight: bold;
padding: 16px 180px;
}
</style>
</head>
<body>
<center>
<div class="calci">
<br><br><br>
<input type="text" placeholder="0" class="text" id="outputscreen"
size="45" ><br><br><br>
<button class="button" onclick="display('7')">7</button>
<button class="button" onclick="display('8')">8</button>
<button class="button" onclick="display('9')">9</button>
<button class="button" onclick="display('%')">%</button><br><br>
<button class="button" onclick="display('4')">4</button>
<button class="button" onclick="display('5')">5</button>
<button class="button" onclick="display('6')">6</button>
<button class="button" onclick="display('*')">*</button><br><br>
<button class="button" onclick="display('3')">3</button>
<button class="button" onclick="display('2')">2</button>
<button class="button" onclick="display('1')">1</button>
<button class="button" onclick="display('-')">-</button><br><br>
<button class="button" onclick="display('.')">.</button>
<button class="button" onclick="display('0')">0</button>
<button class="button" onclick="display('+')">+</button>
<button class="button" onclick="display('/')">/</button><br><br>
<button class="button" onclick="display('(')">(</button>
<button class="button" onclick="display(')')">)</button>
<button class="button" onclick="Clear()">C</button>
<button class="button" onclick="Delete()">D</button><br><br>
<button class="answer" onclick="Calculate()">=</button>
</div>
</center>
<script>
let outputscreen = document.getElementById("outputscreen")
function display(num)
{
outputscreen.value+=num
}
function Clear()
{
outputscreen.value = ""
}
function Delete()
{
outputscreen.value = outputscreen.value.slice(0,-2)
}
function Calculate()
{
try
{
outputscreen.value = eval(outputscreen.value)
}
catch(err)
{
alert("Invalid")
}
}
</script>
</body>
</html>
Output:

5. Aim: Demonstrate Higher order functions with necessary examples – filter(),


reduce() and map()
Program:
<!DOCTYPE html>
<html>
<body>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<script>
const ages = [32,33,16,40]
document.getElementById("p1").innerHTML=ages.map(myfunction)
document.getElementById("p2").innerHTML=ages.filter(checkadult)
document.getElementById("p3").innerHTML=ages.reduce(myfunc)
function myfunction(num){
return num*10
}
function checkadult(age){
return age>18
}
function myfunc(total,n){
return total-n
}
</script>
</body>
</html>
Output:

6. Aim: Create a Class Component for Counter in React JS


Program:
import React, { Component } from 'react'

export default class Counter extends Component {


constructor(props){
super(props)
this.state={count:0}
}
render(){
return(
<button onClick={()=>{this.setState({count:this.state.count+1})}}>count -
{this.state.count}</button>
)
}
}
Output:

7. Aim: Create a Class component for Changing the color of the text given in React JS
Program:
import React, { Component } from 'react'

export default class ColorChange extends Component {


constructor(props){
super(props)
this.state={color : "Magenta"}
}
handlecolor=()=>{this.setState({color : "Green"})}
handlecolor1=()=>{this.setState({color : "cyan"})}
handlecolor2=()=>{this.setState({color : "orange"})}
render() {
return (
<h1 onMouseOver={this.handlecolor} onMouseOut={this.handlecolor1}
onDoubleClick={this.handlecolor2} style={this.state}>
Hi I am Virat from VVIT</h1>
)
}
}
Output:
8. Aim: Create a Class Component for viewing an array of objects in a tabular form.
Program:
import React, { Component } from 'react'

export default class Table extends Component {


constructor(props){
super(props)
this.state=
[{id:101,name:"Venu",age:20},
{id:102,name:"Narasimha",age:20},
{id:103,name:"Ajay",age:19}]
}
render(){
return(
<div>
<table>
<tr>{Object.keys(this.state[0]).map((x)=>(<th>{x}</th>))}</tr>
{this.state.map((Obj) =>
(<tr>{Object.values(Obj).map((y)=>(<td>{y}</td>))}</tr>))}
</table>
</div>
)
}
}
Output:

9. Aim: Display a digital clock in React JS.


Program:
import React, { useState } from "react";
function Clock(){
let time = new Date().toLocaleTimeString();
const [currenttime,setcurrentTime] = useState(time);
const updateTime = () =>{
let time = new Date().toLocaleTimeString();
setcurrentTime(time);
}
setInterval(updateTime, 1000);
return(
<div>
<h1>{currenttime}</h1>
</div>
)
}
export default Clock;
Output:

10. Aim: Demonstrate useState Hook with the help sample text.
Program:
import React, { useState } from 'react'
export default function UseState() {
const [count,setcount]=useState(0);
return (
<div>
<button onClick={()=>{setcount(count+1)}}>+</button>
<h1>count is {count}</h1>
</div>
)
}
Output:

11. Aim: Demonstrate useContext Hook with necessary example.


Program:
import React, { createContext, useContext, useState } from "react";
const global = createContext()
export default function UseContext(){
const [count,setcount]=useState(0)
return(
<global.Provider value={count}>
<div>
<button onClick={handlecount}>+</button>
<h1>count - {count}</h1>
<ChildComp1/>
</div>
</global.Provider>
)
function handlecount(){
setcount(count+1)
}
}
function ChildComp1(){
const cnt = useContext(global)
return(
<div>
<h1>count - {cnt}</h1>
</div>
)
}
Output:

12. Aim: Demonstrate useEffect Hook with necessary example.


Program:
import React, { useEffect, useState } from 'react'

export default function UseEffect() {


const [count,setcount]=useState(0)
const [flag,setflag]=useState("TRUE")
useEffect(()=>{setcount(count+1)},[flag])
return (
<div>
<h1>count is {count}</h1>
<button onClick={handleflag}>{flag}</button>
</div>
)
function handleflag(){
if(flag==="TRUE"){
setflag("FALSE")
}else{
setflag("TRUE")
}
}
}
Output:

13. Aim: Demonstrate consuming web API using fetch & axios (AXIOS API).
Demonstrate with the help of fake URL.
Program:
import React, { useEffect, useState } from "react"
export default function FetchAPI() {
const [user,setuser]=useState([])
useEffect(()=>{
fetch("https://jsonplaceholder.typicode.com/users")
.then((res)=>res.json())
.then((data)=>setuser(data))
.catch((e)=>console.log(e))
})
return (
<div>
{user.map((u)=><p key={u.id}>
user-name = {u.username}
full-name = {u.name}
user-email = {u.email}
</p>)}
</div>
)
}
Output:

b) import React, { useEffect, useState } from 'react'


import axios from 'axios'
export default function Axios() {
const [data,setData]=useState([])

useEffect(()=>{axios.get("https://jsonplaceholder.typicode.com/users").then((response)
=> setData(response.data)).catch((e) => console.log(e))})
return (
<div>
{data.map((user)=><li key={user.id}>
username={user.username}
name={user.name}
email={user.email}
</li>)}
</div>
)
}
Output:

14. Aim: Design a BMI calculator using React JS based on the description given
below:
1. BMI is a measurement of a person's leanness or corpulence based on their
height and weight, and is intended to quantify tissue mass. It is widely used as
a general indicator of whether a person has a healthy body weight for their
height.
2. Formula:
weight (kg) / [height (m)]2 (or) [weight (kg) / height (cm) / height (cm)] x 10,000
3. BMI table for adults: This is the World Health Organization's (WHO)
recommended body weight based on BMI values for adults. It is used for both
men and women, age 18 or older.

Category BMI range -


kg/m2

Severe < 16
Thinness

Moderate 16 - 17
Thinness

Mild Thinness 17 - 18.5

Normal 18.5 - 25

Overweight 25 - 30

Obese Class I 30 - 35

Obese Class II 35 - 40

Obese Class III > 40

Program:
BMI.js
import React, { useState } from 'react'
import './BMI.css'
export default function BMI() {
const [height,setheight]=useState("");
const [weight,setweight]=useState("");
const [name,setname]=useState("");
const CalculateBMI=()=>{
var heightsquared=(height/100*height/100);
var bmi=weight/heightsquared;
if (bmi<16){
alert("Hi "+name+" You are completely UnderWeight (Severe Thinner)")
}
else if(bmi>=16&&bmi<17){
alert("Hi "+name+" You are Moderately UnderWeight (Moderate Thinner)")
}
else if(bmi>=17&&bmi<18.5){
alert("Hi "+name+" You are little UnderWeight (Mild Thinness)")
}
else if(bmi>=18.5&&bmi<=24.99){
alert("Hi "+name+" You are in a healthy weight range")
}
else if(bmi>=25&&bmi<=29.9){
alert("Hi "+name+" You are overweight")
}
else if(bmi>=30){
alert("Hi "+name+" You are obese")
}
else if(bmi<18.5){
alert("Hi "+name+" You are under weight")
}
bmi = Math.round(bmi*100)/100;
}
const handleform=(event)=>{
event.preventDefault();
CalculateBMI();
}
const handlename=(event)=>{
setname(event.target.value);
}
const handleheight=(event)=>{
setheight(event.target.value);
}
const handleweight=(event)=>{
setweight(event.target.value);
}
return (
<div className='container'>
<form onSubmit={handleform}>
<div>
<center>
<h1>BMI CALCULATOR</h1>
NAME : <input type="text" name="name" value={name} onChange =
{handlename}/><br/><br/>
HEIGHT : <input type="text" name="height" value={height} onChange =
{handleheight}/><br/><br/>
WEIGHT : <input type="text" name="weight" value={weight} onChange =
{handleweight}/><br/><br/>
<input type="submit" value="SUBMIT"/>
</center>
</div>
</form>
</div> ) }
BMI.css
.container{
width: 400px;
height: 250px;
background: yellow;
}
Output:
15. Aim: Display a selected set of images in tabular format using React JS.
Program:
ImageGrid.js
import React from "react";
import './Image.css';
const images = [
{
src: "https://images.unsplash.com/photo-1509420316987-
d27b02f81864?dpr=1&auto=format&fit=crop&w=1500&q=80&cs=tinysrgb&ixid=dW5z
cGxhc2guY29tOzs7Ozs%3D",
width: 450,
height: 500,
},
{
src: "https://images.unsplash.com/photo-1509641498745-
13c26fd1ed89?dpr=1&auto=format&fit=crop&w=1000&q=80&cs=tinysrgb&ixid=dW5z
cGxhc2guY29tOzs7Ozs%3D",
width: 450,
height: 500,
},
{
src: "https://images.unsplash.com/photo-1491146179969-
d674118945ff?dpr=1&auto=format&fit=crop&w=1500&q=80&cs=tinysrgb&ixid=dW5zc
Gxhc2guY29tOzs7Ozs%3D",
width: 450,
height: 500,
},
{
src: "https://images.unsplash.com/photo-1509420316987-
d27b02f81864?dpr=1&auto=format&fit=crop&w=1500&q=80&cs=tinysrgb&ixid=dW5z
cGxhc2guY29tOzs7Ozs%3D",
width: 450,
height: 500,
},
{
src: "https://images.unsplash.com/photo-1509641498745-
13c26fd1ed89?dpr=1&auto=format&fit=crop&w=1000&q=80&cs=tinysrgb&ixid=dW5z
cGxhc2guY29tOzs7Ozs%3D",
width: 450,
height: 500,
},
{
src: "https://images.unsplash.com/photo-1491146179969-
d674118945ff?dpr=1&auto=format&fit=crop&w=1500&q=80&cs=tinysrgb&ixid=dW5zc
Gxhc2guY29tOzs7Ozs%3D",
width: 450,
height: 500,
}
];
const ImageGrid = () => {
return (
<div id="img-wrapper">
{images.map((image,index) => {
return (
<div key={index}>
<img src={image.src} height='200px' width='300px' alt=""/>
</div>
);
})}
</div>
);
};
export default ImageGrid;
ImageGrid.css
#img-wrapper{
display: grid;
grid-template-columns: repeat(2,25px);
grid-template-rows: repeat(2,25px);
grid-gap: 170px;
}
Output:
16. Aim: Create a React application to view EMI calculator. A specific view is given
below:

Program:
EMI.js
import React, { useState } from "react";
import './EMI.css';
function EMI() {
const [loan, setLoan] = useState("");
const [tenure, setTenure] = useState("");
const [rate, setRate] = useState("");
const [type, setSelectType] = useState(" ");
const calculateEMI = () => {
var em = loan * rate * ((Math.pow((1+rate),tenure)/(Math.pow((1+rate),tenure)-1)));
alert(em);
};
const submitMe = (e) => {
e.preventDefault();
calculateEMI();
};
const myselect = () => {
var item = document.getElementById("tenureType");
setSelectType(item.options[item.selectedIndex].text);
}
const handleLoanAmount = (e) => {
setLoan(e.target.value);
};
const handleTenure = (e) => {
setTenure(e.target.value);
};
const handleInterestRate = (e) => {
setRate(e.target.value);
};
const clear = () =>{
}
return (
<div className="container">
<center>
<h1>EMI Calculator</h1><br/>
<label>Loan Amount: Rs </label>
<input type="text" name="loan" value={loan}
onChange={handleLoanAmount}/><br/><br/>
<label> Loan Tenure: </label>
<input type="text" name="name" value={tenure} onChange={handleTenure}
/><br/><br/>
<select name="tenureType" id="tenureType" onChange={myselect}>
<option value="Months">Months</option>
<option value="Years">Years</option>
</select><br/><br/>
<label> Interest Rate : </label>
<input type="text" name="rate" value={rate} onChange={handleInterestRate}
/><br/><br/>
<button onClick={submitMe}>Calculate</button><br/><br/>
<button onClick={clear}>Clear</button>
</center>
</div>
);
}
export default EMI;
EMI.css
.container{
width: 400px;
height: 400px;
background: yellow;
}
Output:

17. Aim: Design the following Hotel bill screen. User can select as many items as
possible from the dropdown box and is allowed to enter in the text field provided.
Each transaction must be added in the table given below along with the bill amount.
Program:
import { useRef, useState } from "react";

function HotelBillDemo() {
const selectRef = useRef();
const [quantity, setQuantity] = useState();
const [listItems, setListItems] = useState([]);
const [name, setName] = useState("");

const menu = [
{ itemName: "Briyani", price: 210 },
{ itemName: "Fried Rice", price: 180 },
{ itemName: "Manchuria", price: 120 },
{ itemName: "Gobi Manchurian", price: 130},
{ itemName: "Baby Corn Masala", price: 130},
];

const sdate = new Date();

const handleChange = (e) => {


e.preventDefault();
setName(e.target.value);
setQuantity("");
};

const findSum = () =>{


return listItems?.reduce((acc,item)=> acc+item.totalPrice, 0);
}

const findDuplicate = (name) => {


const index = listItems.findIndex((item)=>{
return item.name === name
})
return index;
};

const handleAddItem = (e) => {


e.preventDefault();
const item = menu.find((item) => {
return item.itemName === name;
});

const itemPrice = item.price


if (name !== "Please Select") {
setQuantity(e.target.value);
const index = findDuplicate(name);

if (listItems.length === 0)
setListItems([{ name, noOfItems: parseInt(e.target.value), totalPrice: itemPrice *
e.target.value}]);
else
if(index!== -1){
const myList = [...listItems];
myList[index].noOfItems = parseInt(myList[index].noOfItems) +
parseInt(e.target.value);
myList[index].totalPrice = myList[index].noOfItems * itemPrice;
setListItems(myList);
}
else
setListItems([...listItems, { name, noOfItems: parseInt(e.target.value), totalPrice:
itemPrice * e.target.value }]);
}
};

const handleDelete = (item) => {


const fitems = listItems.filter((it) => it !== item);
setQuantity('');
setListItems([...fitems]);
};

const tdata = listItems.map((it, index) => (


<tr key={index}>
<td>
{" "}
<span>{it.name} </span>{" "}
</td>
<td>
{" "}
<span>{it.noOfItems} </span>{" "}
</td>
<td>
{" "}
<span>{it.totalPrice} </span>{" "}
</td>
<td>
<button onClick={(e) => {e.preventDefault();
handleDelete(it);}}>x</button>
</td>
</tr>
));

return (
<div className="App">
<h1>GREEN STAR HOTEL</h1>
<h2>Customer Bill</h2>
<h3>
{" "}
Date:{sdate.getDate()}-{sdate.getMonth()+1}-{sdate.getYear() + 1900}
</h3>
<br />
<hr />
<label for="Items">Items:</label>
<select name="itemList" id="itemList" ref={selectRef} onChange={handleChange}>
<option value='Please Select'>Please Select</option>
{
menu.map((item) => {
return <option value={item.itemName}>{item.itemName}</option>;
})
}
</select>
No of Items:
<input type="number" onChange={handleAddItem} value={quantity} />
<hr />
<table align="center" border="1" cellPadding="10%" cellSpacing="10px">
<tr><th>Item Name</th><th>No of Items</th><th>Price</th></tr>
{tdata}
<tr> <td colspan="4">Bill Amount : {findSum()}</td> </tr>
<tr> <td colspan="4">GST (5%): {(0.05*findSum())}</td> </tr>
<tr> <td colspan="4">Amount to be Paid : {findSum()+(0.05*findSum())}</td>
</tr>
</table>
</div>
);
}
export default HotelBillDemo;
Output:
19. Demonstrate the procedure to create a schema in MongoDB.
Program:
db.createCollection("Employees", {
validator: {
$jsonSchema: {
bsonType: "object",
title: "Employee Object Validation",
required: [ "empno", "ename","job","mgr","hiredate","sal","comm","deptno"],
properties: {
empno: {
bsonType: "int",
minimum: 0001,
maximum: 9999,
description: "'empno' must be an int in [0001,9999] and is required"
},
ename: {
bsonType: "string",
description: "'ename' must be a string and is required"
},
job: {
bsonType: "string",
enum:
['CLERK','ANALYST','SALESMAN','MANAGER','PRESEIDENT'],
description: "'job' must be a string in
['CLERK','ANALYST','SALESMAN','MANAGER','PRESEIDENT'] and is required"
},
mgr: {
bsonType: "int",
minimum: 0001,
maximum: 9999,
description: "'mgr' must be an int in [0001,9999] and is
required"
},
hiredate: {
bsonType: "date",
description: "'hiredate' must be a date and is required"
},
sal: {
bsonType: "double",
minimum: 1000.00,
maximum: 10000.00,
description: "'sal' must be a double in [1000.00,10000.00] and
is required"
},
comm: {
bsonType: "int",
minimum: 0,
maximum: 10000,
description: "'comm' must be an int in [0,10000] and is
required"
},
deptno: {
bsonType: "int",
minimum: 10,
maximum: 100,
description: "'deptno' must be an int in [10,100] and is
required"
}
}
}
}
})
Output

20. Demonstrate CRUD operations using MongoDB


Create:
Insert
db.Employees.insertOne(
{'empno':0003,
'ename':'Virat',
'job':'PRESEIDENT',
'mgr':7801,
'hiredate':new Date(1983,2,1,0,1,45),
'sal':new Double(10000),
'comm':400,
'deptno':10})

Read
Update:

Delete

You might also like