Fs QB: Question Bank and Answers
Fs QB: Question Bank and Answers
Fs QB: Question Bank and Answers
Number
String
FS QB 1
undefined
Null
Boolean
Non-primitive data types: The data types that are derived from primitive data types of
the JavaScript language are known as non-primitive data types. It is also known as
derived data types or reference data types.
Object
Array
FS QB 2
What are the limitations of in-browser JavaScript
JavaScript has no direct access to OS functions. It can’t read and write arbitrary
files on the hard disc, copy or execute them.
Different windows/tabs don’t recognize each other. JavaScript from one page is not
able to access the other one, in case they are from different sites. It’s known as
“Same Origin Policy”.
JavaScript allows communication over the net to the server from where the page
comes from. But, its capability of receiving data from the other site is prohibited.
That’s a safety limitation.
//base case
if(n == 0 || n == 1){
return 1;
//recursive case
}
else{
return n * factorial(n-1);
}
let n = 4;
answer = factorial(n)
What is NVM?
nvm is a version manager for node.js, designed to be installed per-user, and invoked
per-shell. nvm works on any POSIX-compliant shell (sh, dash, Ksh, zsh, bash), in
FS QB 3
particular on these platforms: unix, macOS, and windows WSL.
NVM allows users to:
Locally download any of the remote Long Term Support (LTS) versions of Node.js
with a simple command.
Easily switch between multiple versions of Node.js, right from the command line.
PART B
<!DOCTYPE html>
<html>
<head>
<title>Student Information Form</title>
<script type="text/javascript">
function valid()
{
var na = document.getElementById("nm").value;
var ag = document.getElementById("age").value;
var ge = document.getElementById("gender").value;
var em = document.getElementById("eid").value.indexOf("@");
if(na==""||na==null)
{
alert("Enter The Name");
return false;
}
else if(isNaN(ag)||ag<1||ag>100)
{
alert("The age must be a number between 1 and 100");
return false;
}
FS QB 4
else if(ge==""||ge==null)
{
alert("Please Select Gender");
return false;
}
else if(em==-1)
{
alert("E-mail ID is not valid");
return false;
}
}
else
{
alert("The Student Information Submitted Successfully");
}
</script>
</head>
<body>
<center><b>
<h3>Student Information Form</h3>
<form action="" onsubmit="return valid()" method="post">
Name: <input type="text" id="nm"><br><br>
Age: <input type="text" id="age"><br><br>
<label for="gender">Please selecr your gender</label>
<select id="gender">
<option value="man">Man</option>
<option value="woman" selected>Woman</option>
<option value="other">Other</option>
</select><br><br>
Email id: <input type="text" id="eid"><br><br>
<input type="submit" value="Submit">
</form>
</b></center>
</body>
</html>
Components include Mongo DB, Angular JS, Components include Mongo DB, React JS,
Express, and Node Express, and Node.
FS QB 5
MEAN MERN
PART C
FS QB 6
Design a Passenger Registration form with First Name, Last name,
Address, City, State, Country, Pincode, Username and Password
fields for a General login webpage and satisfy the following
criteria:
(a) Check that the First Name, Last Name, City, Country, Username, and Password
fields are filled out.
(b) Check that the Pincode is exactly 6 numerics.
<HTML>
<HEAD>
<TITLE>WEB PAGE DESIGN WITH JAVA SCRIPT</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function validate()
{
if(document.form1.fname.value.length==0)
{
alert("Enter first name");
document.form1.fname.focus();
return;
}
if(document.form1.lname.value.length==0)
{
alert("Enter last name");
document.form1.lname.focus();
return;
}if(document.form1.uname.value.length==0)
{
alert("Enter user name");
document.form1.uname.focus();
return;
}
if(document.form1.pswrd.value.length==0)
{
alert("Enter password");
document.form1.pswrd.focus();
return;
}
if(document.form1.city.value.length==0)
{
alert("Enter the city");
document.form1.city.focus();
FS QB 7
return;
} if(document.form1.country.value.length==0)
{
alert("Enter the country");
document.form1.country.focus();
return;
}if(!document.form1.mail.includes('@'))
{
alert("Enter the valid email");
document.form1.mail.focus();
return;
}
document.writeln("<BODY><H1>SUCCESS!!</H1></BODY>");
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="form1">
<H1>Passenger Registration</H1>
<HR></HR>
FIRST NAME <INPUT type="text" name="fname" />
LAST NAME <INPUT type="text" name="lname" /> </br>
ADDRESS <TEXTAREA rows="5" name="address"/></TEXTAREA> </br>
CITY <INPUT type="text" name="city" /> </br>
STATE <INPUT type="text" name="state" maxlength="3" /> </br>
COUNTRY <INPUT type="text" name="country" /> </br>
PINCODE <INPUT type="text" name="pin" maxlength="6" /> </br>
E-MAIL <INPUT type="email" name="mail"/> </br>
USERNAME <INPUT type="text" name="uname" />
PASSWORD <INPUT type="password" name="pswrd" /> </br>
<INPUT type="submit" value="SUBMIT" onclick="validate()">
<INPUT type="reset" value="CLEAR"> </br>
</FORM>
</BODY>
</HTML>
Design a webpage with a text box where the user can enter a four
digit number with a validation button. The digits entered here must
be in ascending order for the input (eg 1234,5678). Validate the
field using JavaScript.
<HTML>
<HEAD>
FS QB 8
<SCRIPT LANGUAGE="JavaScript">
return;
}
}
document.writeln("<BODY><H1>VALID!!</H1></BODY>");
}
</SCRIPT>
</HEAD>
<BODY>
<HR></HR>
</FORM>
</BODY>
</HTML>
FS QB 9
Write JavaScript for the following.
Provide a text box for the user to enter username. Validate the user name must
contain eight characters. Provide submit button for the validation to happen. On
successful validation display a new page with an image and two textboxes for
entering width and height of the image respectively with a resize button at the
bottom of the image. On clicking the resize button validate the width and height
on successful validation display the image.
index.html
<!DOCTYPE html>
<html>
<head>
<title>WEB PAGE DESIGN WITH JAVA SCRIPT</title>
<script language="JavaScript">
function validate()
{
var name = document.form1.uname.value
if(name.length !=8) {
alert("Name must have 8 characters");
return;
}
window.location.href = './imageScreen.html';
}
</script>
</head>
<body>
<form name="form1">
<h1>Name</h1>
<hr>
USERNAME <input type="text" name="uname" />
<input type="submit" value="VALIDATE" onclick="validate()" >
</form>
</body>
</html>
imageScreen.html
<html>
<head>
FS QB 10
<script language="JavaScript">
}
event.preventDefault();
}
</script>
</head>
<body>
<h1>Image</h1>
<hr>
<br>
</form>
</body>
</html>
FS QB 11
You can run the project by typing the command cd my-app.
cd my-app
npm start
Step 3: Create a React app. Now to create an app we will use the boilerplate we
installed. The below command will create an app named myapp.
create-react-app myapp
Step 4: Start the development server. To start the development server, go inside your
current directory “myapp” and execute the below command:
npm start
When we create a new react app using the npx create-react-app command, the default
port for the app is 3000. We can access the app from the localhost:3000.
FS QB 12
No, it doesn’t require Node.js, but it would be very difficult to build a project without it
since you need it to use almost all React libraries, which are Node.js packages.
Also, without Node.js, you can’t use Create React App, which makes creating the
project
and building very quick and easy.
ES6 provides a new way of declaring a constant by using the const keyword. The const
keyword creates a read-only reference to a value. By convention, the constant
identifiers
are in uppercase. Like the let keyword, the const keyword declares blocked-scope
variables.
5. What is GitHub?
GitHub is a code hosting platform for collaboration and version control. GitHub lets you
(and others) work together on projects. Sign up for GitHub at https://github.com/:
GitHub essentials are: Repositories.
In simple words, virtual DOM is just a copy of the original DOM kept in the memory and
synced with the real DOM by libraries such as ReactDOM. This process is called
Reconciliation. Virtual DOM has the same properties that of the Real DOM, but it lacks
the power to directly change the content of the screen.
FS QB 13
7. What is the correct command to create a new React project?
You create a new React project with the command create-react-app , followed by the
name of your project. For example: create-react-app my-app.
Ans: render
GitHub, meanwhile, serves as a host for Git repository teams to store their code in a
centralized location. While Git is a tool that's used to manage multiple versions of
source
code edits that are then transferred to files in a Git repository, GitHub serves as a
location for uploading copies of a Git repository.
Repository: A directory or storage space where your projects can live. Sometimes
FS QB 14
GitHub
users shorten this to “repo.” It can be local to a folder on your computer, or it can be a
storage space on GitHub or another online host. You can keep code files, text files,
image
files, you name it, inside a repository.
You can run any one of the below mentioned commands to start the node server for
your ReactJS application:
npm run-script start.
npm start.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>React Local</title>
<!-- Import the React, React-Dom and Babel libraries from unpkg -->
<script type="application/javascript" src="https://unpkg.com/react@16.0.0/umd/react.prod
uction.min.js"></script>
<script type="application/javascript" src="https://unpkg.com/react-dom@16.0.0/umd/react-
dom.production.min.js"></script>
<script type="application/javascript" src="https://unpkg.com/babel-standalone@6.26.0/bab
el.js"></script>
FS QB 15
</head>
<body>
<div id="root"></div>
<script type="text/javascript">
</script>
</body>
</html>
Steps are :
Initiate a local git repository on your computer.
git init
FS QB 16
git push origin master
Answer 14
FS QB 17
connection.connect((err) => {
if (err) throw err;
console.log("Connected!");
var sql = "CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255), createdDate DA
TETIME DEFAULT NOW())";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
});
app.get("/insert",(req,res) => {
var sql = "INSERT INTO customers (name, address) VALUES ('Company Inc', 'Highway 37')";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
app.get("/fetch",(req,res) => {
connection.query('SELECT * from users LIMIT 5 ORDER BY createdDate', (err, rows) => {
if(err) throw err;
console.log('The data from users table are: \n', rows);
res.send(rows);
});
});
app.listen(3000, () => {
console.log('Server is running at port 3000');
});
16. How can you check the installed version of Node JS?
Test Node. To see if Node is installed, open the Windows Command Prompt,
and type
node -v.
FS QB 18
This should print the version number so you’ll see something like this v0.10.35.
npm -v
This should print the version number so you’ll see something like this 1.4.28
Create a test file and run it. A simple way to test that node.js works is to
create a simple JavaScript file: name it hello.js, and just add the code
console.log('Node is installed!');.
To run the code simply open your command line program, navigate to the folder where
you save the file and type
node hello.js
This will start Node.js and run the code in the hello.js file.
You should see the output Node is installed!
Reason behind node.js uses Single Threaded Event Loop Model architecture:
FS QB 19
based implementation when the application isn’t doing CPU intensive stuff and can
run thousands more concurrent connections than Apache or IIS or other thread-
based servers.
There is also a very well known and criticized issue with the one thread per
request model for a server which is that they don’t scale very well for several
scenarios compared to the event loop thread model, in short, they lack scalability as
the application grows to meet the future demands and with the addition of new
features.
FS QB 20
app.listen(process.env.PORT || 3000, function () {
console.log(
"Express server listening on port %d in %s mode",
this.address().port,
app.settings.env
);
});
<body>
<button id="btn">Click me</button>
<script>
function test() {
alert("The function 'test' is executed");
}
let btn =document.getElementById("btn");
btn.addEventListener('click', event => {
test();
});
</script>
</body>
or
<body>
<button onclick="test()">Click me</button>
<script>
function test() {
alert("The function 'test' is executed");
}
</script>
</body>
FS QB 21
20.Write a node JS content script to send an email with default
content and
also another node.js script to retrieve email value from redis and
send the
current IP address of the email logged into the user as a mail.
👻
let info = await transporter.sendMail({
from: '"Fred Foo " foo@example.com', // sender address
to: "bar@example.com, baz@example.com", // list of receivers
subject: "Hello ✔", // Subject line
text: "Hello world?", // plain text body
html: "<b>Hello world?</b>", // html body
});
FS QB 22
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
}
main().catch(console.error);
child processes
The child_process module provides the ability to spawn new processes which has their
own memory. The communication between these processes is established through IPC
(inter-process communication) provided by the operating system.
There are mainly three methods inside this module that we care about.
child_process.spawn()
child_process.fork()
child_process.exec()
Cluster
Cluster is mainly used for vertically (adding more power to your existing machine) scale
your nodejs web server. It is built on top of the child_process module. In an Http server,
the cluster module uses child_process.fork() to automatically fork processes and sets
up a master-slave architecture where the parent process distributes the incoming
request to the child processes in a round-robin fashion. Ideally, the number of
processes forked should be equal to the number of cpu cores your machine has.
FS QB 23
Serving static files in Express
To serve static files such as images, CSS files, and JavaScript files, use
the express.static built-in middleware function in Express.
express.static(root, [options])
The root argument specifies the root directory from which to serve static assets. For
more information on the options argument, see express.static.
For example, use the following code to serve images, CSS files, and JavaScript files in
a directory named public :
app.use(express.static('public'))
Now, you can load the files that are in the public directory:
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
Express looks up the files relative to the static directory, so the name of the static
directory is not part of the URL.
To use multiple static assets directories, call the express.static middleware function
multiple times:
FS QB 24
app.use(express.static('public'))
app.use(express.static('files'))
Express looks up the files in the order in which you set the static directories with
the express.static middleware function.
app.use('/static', express.static('public'))
Now, you can load the files that are in the public directory from the /static path prefix.
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
However, the path that you provide to the express.static function is relative to the
directory from where you launch your node process. If you run the express app from
another directory, it’s safer to use the absolute path of the directory that you want to
serve:
FS QB 25
The Built-in HTTP Module
Node.js has a built-in module called HTTP, which allows Node.js to transfer data over
the Hyper Text Transfer Protocol (HTTP).
var http = require('http');
var fs = require('fs');
Read files
Create files
Update files
Delete files
Rename files
var url = require('url');
FS QB 26
Parse an address with the url.parse() method, and it will return a URL object with each
part of the address as properties
Events Module
Node.js has a built-in module, called "Events", where you can create-, fire-, and listen
for- your own events.
To include the built-in Events module use the require() method. In addition, all event
properties and methods are an instance of an EventEmitter object. To be able to access
these properties and methods, create an EventEmitter object:
var events = require('events');
var eventEmitter = new events.EventEmitter();
FS QB 27
password : 'password',
database : 'databasename'
});
connection.connect((err) => {
if (err) throw err;
console.log("Connected!");
var sql = "CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255), createdDate DA
TETIME DEFAULT NOW())";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
});
app.get("/insert",(req,res) => {
var sql = "INSERT INTO customers (name, address) VALUES ('Company Inc', 'Highway 37')";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
app.get("/fetch",(req,res) => {
connection.query('SELECT * from users LIMIT 5 ORDER BY createdDate', (err, rows) => {
if(err) throw err;
console.log('The data from users table are: \n', rows);
res.send(rows);
});
});
app.listen(3000, () => {
console.log('Server is running at port 3000');
});
25. Write a node JS server code to integrate with NOSQL database and do the
following operation:
a). Create a database of your own and insert the given data into the table.
FS QB 28
b). Fetch the record by joining the table
- Search criteria
- Recent data order
- Limit first 5 records
Install node js
Run the command node filename.js to see the output in the terminal .
Install express:
npm i express
2) What is MongoDB?
FS QB 29
MongoDB is a document-oriented NoSQL database used for high volume data
storage. Instead of using tables and rows as in the traditional relational databases,
MongoDB makes use of collections and documents. Documents consist of key-
value pairs which are the basic unit of data in MongoDB. Collections contain sets of
documents and function which are the equivalent of relational database tables.
MongoDB stores data in flexible, JSON-like documents, meaning fields can vary
from document to document and data structure can be changed over time
Connect to Studio 3T
FS QB 30
Import data in JSON, CSV, BSON/mongodump or SQL
Paste your Mongo url in an env file with specified username and password.
Create a database schema model in a separate file to store data in the collections in
the mongodb
Make a function in the database file and setup general properties and if error occurs
display it in the console
FS QB 31
7) Steps to Set port in Database connection for application.
Initialise dotenv module .
Make a variable PORT and set up a custom port and default port for running our
application.
Sample file:
const dotenv = require('dotenv');
dotenv.config( { path : 'config.env'} )
const PORT = process.env.PORT || 8080
Sample file:
FS QB 32
9) Indexing :
MongoDB uses indexing in order to make the query processing more efficient. If there is
no indexing, then the MongoDB must scan every document in the collection and retrieve
only those documents that match the query. Indexes are special data structures that
store some information related to the documents such that it becomes easy for
MongoDB to find the right data file. The indexes are ordered by the value of the field
specified in the index.
Creating an Index :
MongoDB provides a method called createIndex() that allows users to create an index.
Syntax –
db.COLLECTION_NAME.createIndex({KEY:1})
FS QB 33
Pagination :
MongoDB pagination provides an efficient way to model the data which makes the
paging fast and efficient, in MongoDB we can explore a large number of data quickly
and easily. The most important use of paging implementation is it used the skip, limit,
and sort in database level, but limit and skip have some problems to use in database
level. The pagination is nothing but the retrieve next page by using the previous page.
To faster access data, we can create the index on the collections field in MongoDB.
Syntax:
Below is the syntax of MongoDB pagination.
1) MongoDB pagination by using limit method
db.collection_name.find () .limit (number);
10) Aggregation :
In MongoDB, aggregation operations process the data records/documents and return
computed results. It collects values from various documents and groups them together
and then performs different types of operations on that grouped data like sum, average,
minimum, maximum, etc to return a computed result. It is similar to the aggregate
function of SQL.
Syntax:
Let us view the general syntax of the MongoDB aggregate() method written as follows:
Db.NAME_OF_COLLECTION.aggregate(AGGREGATE_OPERATION);
FS QB 34
MongoDB provides three ways to perform aggregation
Aggregation pipeline
Map-reduce function
Single-purpose aggregation
Aggregation Pipeline
:
MAP-REDUCE FUNCTION:
FS QB 35
SINGLE PURPOSE AGGREGATION:
DISTINCT:
FS QB 36
COUNT:
GROUP:
FS QB 37
11)Node.js Send an Email.
The Nodemailer module makes it easy to send emails from your computer.
Use the username and password from your selected email provider to send an
email.
Code:
FS QB 38
Create a Node.js file that writes an HTML form, with an upload field.
Include the Formidable module to be able to parse the uploaded file once it reaches
the server.
When the file is uploaded and parsed, it gets placed on a temporary folder on your
computer.
The path to this directory can be found in the "files" object, passed as the third
argument in the parse() method's callback function.
Sample code:
13) Projection :
Projection allows you to select only the necessary data rather than selecting whole data
from the document. For example, a document contains 5 fields, i.e.,
FS QB 39
{
name: "Roma",
age: 30,
branch: EEE,
department: "HR",
salary: 20000
}
But we only want to display the name and the age of the employee rather than
displaying whole details. Now, here we use projection to display the name and age of
the employee.
One can use projection with the db.collection.find() method. In this method, the second
parameter is the projection parameter, which is used to specify which fields are returned
in the matching documents.
Syntax:
db.collection.find({}, {field1: value2, field2: value2, ..})
If the value of the field is set to 1 or true, then it means the field will be included in
the return document.
If the value of the field is set to 0 or false, then it means the field will not be included
in the return document.
FS QB 40
By doing this, will get redundancy and increase data availability with multiple copies of
data on different database servers. So, it will increase the performance of reading
scaling. The set of servers that maintain the same copy of data is known as replica
servers or MongoDB instances.
Sharding is a method for allocating data across multiple machines. MongoDB used
sharding to help deployment with very big data sets and large throughput the operation.
By sharding, you combine more devices to carry data extension and the needs of read
and write operations.
Create or insert operations add new documents to a collection. If the collection does not
currently exist, insert operations will create the collection.
MongoDB provides the following methods to insert documents into a collection:
FS QB 41
db.collection.insertOne() - It is used to insert a single document in the collection.
Read :
Read operations retrieve documents from a collection; i.e. query a collection for
documents. MongoDB provides the following methods to read documents from a
collection:
Update :
FS QB 42
db.collection.replaceOne() It is used to replace single document in the
collection that satisfy the given criteria.
Delete :
FS QB 43
16. How to Download & Install MongoDB on Windows
You can install MongoDB using two different methods one is using msi and another is
using zip. Here, we will discuss how to install MongoDB using msi, so you need to
follow each step carefully:
Step 1: Go to MongoDB Download Center to download MongoDB Community Server.
Here, You can select any version, Windows, and package according to your
requirement.
Step 2: When the download is complete open the msi file and click the next button in the
startup screen:
Step 3: Now accept the End-User License Agreement and click the next button:
Step 4: Now select the complete option to install all the program features. Here, if you
can want to install only selected program features and want to select the location of the
installation, then use the Custom option:
Step 5: Select “Run service as Network Service user” and copy the path of the data
directory. Click Next:
Step 6: Click the Install button to start the installation process:
Step 7: After clicking on the install button installation of MongoDB begins:
Step 8: Now click the Finish button to complete the installation process:
Step 9: Now we go to the location where MongoDB installed in step 5 in your system
and copy the bin path:
Step 10: Now, to create an environment variable open system properties <<
Environment Variable << System variable << path << Edit Environment variable and
paste the copied link to your environment system and click Ok:
Step 11: After setting the environment variable, we will run the MongoDB server, i.e.
mongod. So, open the command prompt and run the following command:
mongod
The MongoDB server(i.e., mongod) will run successfully.
FS QB 44
17) How to create a backup in MongoDB?
To create backup of database in MongoDB, you should use mongodump command.
This command will dump the entire data of your server into the dump directory. There
are many options available by which you can limit the amount of data or create backup
of your remote server.The basic syntax of mongodump command is as follows −
>mongodump
To restore backup data MongoDB's mongorestore command is used. This command
restores all of the data from the backup directory.
Syntax
The basic syntax of mongorestore command is −
>mongorestore
FS QB 45
Use the sort() method to sort the result in ascending or descending order. This method
takes one parameter, an object defining the sorting order.
db.collection("customers").find().sort({price: 1})
In this example the customers' documents are sorted based on the price field in
ascending order.
The limit() method takes one parameter, a number defining how many documents to
return.
db.collection("customers").find().limit(5)0
EXAMPLE
To connect to a MongoDB instance running on localhost with a non-default port 28015:
mongosh "mongodb://localhost:28015”
mongosh --host mongodb0.example.com --port 28015
FS QB 46
22)List five commonly used commands in mongosh:
show databases,
show collections (of current database),
use <db-name> (to switch to a database),
version() (for shell version),
quit and
exit.
getCollectionNames(),
createCollection(),
dropDatabase(), and
stats().
insert(),
find(),
update(),
deleteOne(),
FS QB 47
aggregate(),
count(),
distinct(),
remove(),
createIndex(),
dropIndex(), and
stats()
$inc (increment),
and $unset.
FS QB 48
It supports AND, OR and XOR updates of integers.
Many other features such as primary keys and transactions are equivalent though
not the same.
However, it's possible to add or drop fields using the method updateMany()
Document Oriented
Key Value
Graph
Column Oriented
FS QB 49
MongoDB is a document oriented database. It stores data in the form of BSON structure
based documents. These documents are stored in a collection.
FS QB 50
32.What is Replication in MongoDB? Explain.
Replication is the process of synchronizing data across multiple servers. Replication
provides redundancy and increases data availability. With multiple copies of data on
different database servers, replication protects a database from the loss of a single
server. Replication also allows you to recover from hardware failure and service
interruptions.
MongoDB supports field, range-based, string pattern matching type queries. for
searching the data in the database
FS QB 51
Explain step-by-step procedure to connect MongoDB database to
Express server.
require("dotenv").config(); // environment variable
// require packages
// initialise express
mongoose
.connect(
process.env.MONGODB_URI,
// create a schema
roll_no: Number,
name: String,
year: Number,
subjects: [String]
});
FS QB 52
roll_no: 1001,
year: 3,
});
// if(err) console.log(err);
// });
// get documents
if (!err) {
res.send(found);
} else {
console.log(err);
});
});
// Server listen
FS QB 53
How do you start working on a specific MongoDB Database
through mongo shell?
Local MongoDB Instance on a Non-default Port
To explicitly specify the port, include the --port command-line option. For example, to
connect to a MongoDB instance running on localhost with a non-default port 28015:
mongo --port 28015
MongoDB Instance on a Remote Host .To explicitly specify the hostname and/or port,
You can specify a connection string. For example, to connect to a MongoDB instance
running on a remote host machine:
mongo "mongodb://mongodb0.example.com:28015"
What is the command syntax that tells you whether you are on the
master server or not? And how many master does MongoDB
allow?
Command syntax Db.isMaster() will tell you whether you are on the master server or
not. MongoDB allows only one master server.
FS QB 54
Write a program to connect a MongoDB database to Node.js?
Approach:-
First, initialize the node.js project in the particular folder in your machine.
Step 1: Create a NodeJS Project and initialize it using the following command:
npm init
Step 2: Install the node modules using the following command:
npm i express mongodb mongoose cors
File Structure: Our file structure will look like the following:
index.js
FS QB 55
useUnifiedTopology: true,
},
(err) =>
err ? console.log(err) : console.log("Connected to yourDB-name database")
);
const express = require("express");
const app = express();
const cors = require("cors");
console.log("App listen at port 5000");
FS QB 56
Is Express.js front-end or backend framework?
js, or simply Express, is a back end web application framework for Node. js, released as
free and open-source software under the MIT License. It is designed for building web
applications and APIs. It has been called the de facto standard server framework for
Node.
FS QB 57
Express.js is a framework based on Node.js for which is used for building web-
application using approaches and principles of Node.js.event-driven.
FS QB 58
curl -fsSL https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -
cURL is a command line tool available on many operating systems used to transfer
data. It reads whatever data is stored at the URL passed to it and prints the content to
the system’s output. In the following example, cURL prints the content of the GPG key
file and then pipes it into the following sudo apt-key add - command, thereby adding the
GPG key to your list of trusted keys.
This command will return OK if the key was added successfully:
Output
OK
At this point, your APT installation still doesn’t know where to find the mongodb-org
package you need to install the latest version of MongoDB.
Run the following command, which creates a file in the sources.list.d directory named
mongodb-org-4.4.list. The only content in this file is a single line reading deb [
arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4
multiverse:
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4
multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list
This single line tells APT everything it needs to know about what the source is and
where to find it:
After running this command, update your server’s local package index so APT knows
where to find the mongodb-org package:
sudo apt update
When prompted, press Y and then ENTER to confirm that you want to install the
package.
When the command finishes, MongoDB will be installed on your system. However it
isn’t yet ready to use. Next, you’ll start MongoDB and confirm that it’s working correctly.
FS QB 59
What is Middleware in Express.js? What are the different types of
Middleware?
Middleware functions are functions that have access to the request object (req), the
response object (res), and the next middleware function in the application’s request-
response cycle. The next middleware function is commonly denoted by a variable
named next.
Middleware functions can perform the following tasks:
Execute any code.
Make changes to the request and the response objects.
End the request-response cycle.
Call the next middleware function in the stack.
If the current middleware function does not end the request-response cycle, it must
call next() to pass control to the next middleware function. Otherwise, the request
will be left hanging.
Application-level middleware
Router-level middleware
Error-handling middleware
Built-in middleware
Third-party middleware
Application-level middleware
Bind application-level middleware to an instance of the app object by using the
app.use() and app.METHOD() functions, where METHOD is the HTTP method of the
request that the middleware function handles (such as GET, PUT, or POST) in
lowercase.
const express = require('express')
const app = express()
FS QB 60
app.use((req, res, next) => {
console.log('Time:', Date.now())
next()
})
Router-level middleware
Router-level middleware works in the same way as application-level middleware, except
it is bound to an instance of express.Router().
const router = express.Router()
Error-handling middleware
Error-handling middleware always takes four arguments. You must provide four
arguments to identify it as an error-handling middleware function. Even if you don’t need
to use the next object, you must specify it to maintain the signature. Otherwise, the next
object will be interpreted as regular middleware and will fail to handle errors.
Built-in middleware
Starting with version 4.x, Express no longer depends on Connect. The middleware
functions that were previously included with Express are now in separate modules; see
the list of middleware functions.
Third-party middleware
Use third-party middleware to add functionality to Express apps.
Install the Node.js module for the required functionality, then load it in your app at the
application level or at the router level.
FS QB 61
The following example illustrates installing and loading the cookie-parsing middleware
function cookie-parser.
Your system should display example_db (or the name you specified).
example of using the db command checking database name
2. List all the databases on your system with the show dbs command:
show dbs
FS QB 62
The newly created database is empty – you’ll need to insert data for it to display in this
list
Add MongoDB Collection with insert() Command
A collection in MongoDB is much like a table in other database applications.
The following command creates a record and inserts it into a newly created collection. A
record is a document with field names and values. As with a new database, if this
record does not exist, MongoDB creates it:
db.Sample.insert({"SampleValue1" : 255, "SampleValue2" : "randomStringOfText"})
Let’s take a closer look at the syntax of the command to understand how the record and
collection are created.
db.Sample.insert – This is the insert command. In this example, the name Sample
represents the name of the document you’re inserting data into. If the document does
not already exist, MongoDB automatically creates it.
({ }) – The set of brackets encloses the data you are entering. Note that there’s a set of
close-brackets at the end.
"SampleValue1" : 255, "SampleValue2" : "randomStringOfText" – Represents the
format of the data we are entering into the record.
After you execute the command, you see the following response:
WriteResult({ "nInserted" : 1})
This response confirms that the system automatically created a collection and the
record was inserted into said collection.
MongoDB confirms that you have successfully inserted data to a new collection
If you list the existing databases with the show dbs command, you’ll notice that the
example_db database is now on the list.
FS QB 63
A file named package.json is made within the folder created.
“npm install” command is run on the electronic communication. It installs all the
libraries gift in package.json.
“Router” file is made within the package that consists of a folder named index.js.
“App” is made within the package that has the index.html file.
{ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
MongoDB Shell
You can run the operation in the web shell below:
insertOne() returns a document that includes the newly inserted document's _id field
value. For an example of a return document, see db.collection.insertOne() reference.
To retrieve the document that you just inserted, query the collection:
db.inventory.find( { item: "canvas" } )
MongoDB Shell
Insert Multiple Documents
FS QB 64
➤ Use the Select your language drop-down menu in the upper-right to set the language
of the examples on this page.
New in version 3.2.
db.collection.insertMany() can insert multiple documents into a collection. Pass an array
of documents to the method.
The following example inserts three new documents into the inventory collection. If the
documents do not specify an _id field, MongoDB adds the _id field with an ObjectId
value to each document. See Insert Behavior.
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" }},
{ item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
{ item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom:"cm"}}
])
Delete Documents
➤ Use the Select your language drop-down menu in the upper-right to set the language
of the following examples.
db.collection.deleteOne()
The examples on this page use the inventory collection. To populate the inventory
collection, run the following:
db.inventory.insertMany( [
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },
] );
FS QB 65
Connect to your database from a Node.js application
Import MongoClient
The MongoDB module exports MongoClient, and that’s what we’ll use to connect to a
MongoDB database. We can use an instance of MongoClient to connect to a cluster,
access the database in that cluster, and close the connection to that cluster.
const {MongoClient} = require('mongodb');
Now we're ready to use MongoClient to connect to our cluster. client.connect() will
return a promise. We will use the await keyword when we call client.connect() to
indicate that we should block further execution until that operation has completed.
await client.connect();
Now we are ready to interact with our database. Let's build a function that prints the
names of the databases in this cluster. It's often useful to contain this logic in well
named functions in order to improve the readability of your codebase. Throughout this
series, we'll create new functions similar to the function we're creating here as we learn
how to write different types of queries. For now, let's call a function named
listDatabases().
await listDatabases(client);
Let’s wrap our calls to functions that interact with the database in a try/catch statement
so that we handle any unexpected errors.
try {
await client.connect();
await listDatabases(client);
} catch (e) {
FS QB 66
console.error(e);
We want to be sure we close the connection to our cluster, so we’ll end our try/catch
with a finally statement.
finally {
await client.close();
Once we have our main() function written, we need to call it. Let’s send the errors to the
console.
main().catch(console.error);
Putting it all together, our main() function and our call to it will look something like the
following.
async function main(){
try {
await client.connect();
await listDatabases(client);
} catch (e) {
console.error(e);
} finally {
await client.close();
main().catch(console.error);
console.log("Databases:");
FS QB 67
};
FS QB 68
Step 3) Choose which Field Name’s you want to modify and enter their new value
accordingly.
db.Employee.update
(
{
Employeeid : 1
},
{
$set :
{
"EmployeeName" : "NewMartin",
"Employeeid" : 22
}
}
)
If the command is executed successfully and if you run the “find” command to search for
the document with Employee id as 22
FS QB 69
Read :
Read operations retrieve documents from a collection; i.e. query a collection for
documents. MongoDB provides the following methods to read documents from a
collection:
MongoDB provides the following methods to retrieve documents into a collection:
Update :
Update operations modify existing documents in a collection. MongoDB provides the
following methods to update documents of a collection
FS QB 70
Delete :
Delete operations remove documents from a collection. MongoDB provides the
following methods to delete documents of a collection:
FS QB 71
Explain Error Handling In Express.js Using An Example?
Error Handling
Error Handling refers to how Express catches and processes errors that occur both
synchronously and asynchronously. Express comes with a default error handler so you
don’t need to write your own to get started.
Catching Errors
It’s important to ensure that Express catches all errors that occur while running route
handlers and middleware.
Errors that occur in synchronous code inside route handlers and middleware require
no extra work. If synchronous code throws an error, then Express will catch and process
it. For example:
app.get('/', (req, res) => {
})
For errors returned from asynchronous functions invoked by route handlers and
middleware, you must pass them to the next() function, where Express will catch and
process them. For example:
app.get('/', (req, res, next) => {
if (err) {
} else {
res.send(data)
})
})
Starting with Express 5, route handlers and middleware that return a Promise will call
next(value) automatically when they reject or throw an error. For example:
app.get('/user/:id', async (req, res, next) => {
FS QB 72
res.send(user)
})
If getUserById throws an error or rejects, next will be called with either the thrown error
or the rejected value. If no rejected value is provided, next will be called with a default
Error object provided by the Express router.
If you pass anything to the next() function (except the string 'route'), Express regards
the current request as being an error and will skip any remaining non-error handling
routing and middleware functions.
If the callback in a sequence provides no data, only errors, you can simplify this code as
follows:
app.get('/', [
},
res.send('OK')
])
In the above example next is provided as the callback for fs.writeFile, which is called
with or without errors. If there is no error the second handler is executed, otherwise
Express catches and processes the error.
FS QB 73
Gain in-depth knowledge and become an expertENROLL NOW
Cross-check the Specifications and Download MongoDB
Under the Software section, click on the Community server version.
MongoDB_Installation
Make sure that the specifications to the right of the screen are correct. At the time of
writing, the latest version is 4.4.5. Ensure that the platform is Windows, and the
package is MSI. Go ahead and click on download.
Installation_MongoDB.
MongoDB Installation
You can find the downloaded file in the downloads directory. You can follow the steps
mentioned there and install the software.
MongoDB_Setup
Setup_MongoDB
On completing the installation successfully, you will find the software package in your C
drive. C:\Program Files\MongoDB\Server\4.4\bin.
/MongoDB.
You can see that there are mongo and mongod executable files. The mongod file is the
daemon process that does the background jobs like accessing, retrieving, and updating
the database.
Create an Environment Variable
It’s best practice to create an environment variable for the executable file so that you
don’t have to change the directory structure every time you want to execute the file.
Mongo_EnvironmentVariable
EnvVariable_MongoDB.
MongoDB Developer and Administrator: Free Course
MongoDB Developer & Administrator Basics for FREESTART LEARNING
Execute the Mongo App
After creating an environment path, you can open the command prompt and just type in
mongo and press enter.
FS QB 74
Mongo_Setup.
The mongo server is then generated and is up and running.
Big Data Engineer Master's Program
Master All the Big Data Skill You Need TodayENROLL NOW
Verify the Setup
To verify if it did the setup correctly, type in the command show DBS.
Setup_Mongo
With that, you have successfully installed and set up MongoDB on your Windows
system.
MongoDB_Example
This demo sample has also created a database called mydatabase, with some data
added to it. It has also displayed the same using the find() method
Step 2: Initialise the express app and make it listen to a port on localhost.
const express = require("express");
FS QB 75
1. Connection code
Provide the MongoDB URI of your cluster to mongoose.connect() ( refer to this article
for creating a free-tier cluster for MongoDB in the cloud)
mongoose.connect(
process.env.MONGODB_URI,
useNewUrlParser: true,
useUnifiedTopology: true
);
Create a .env file and provide your credentials there in the provided format (key=value)
MONGODB_URL="your-mongodb-uri-here"
Make sure you included .env file along with node_modules directory in .gitignore.
.gitignore file
2. Define a schema
Let’s create a schema for a new collection.
Schema defines the structure of the document, with all the field names and type.
const studentSchema = new mongoose.Schema({
roll_no: Number,
name: String,
year: Number,
subjects: [String]
});
FS QB 76
Name of the property is the fields for the document
Value for the property represents the type for the particular field.
To make any field required, make required as true.
roll_no: {
type: Number,
required: true
Since we wanted to specify that it is required i.e. to send another information along with
the type of the field, we represent the values that are to be sent in an object.
To know more about the schema types, read the documentation here.
3. Define the model
Let’s create our model by passing in the schema and a name for our model.
const Student = mongoose.model('Student', studentSchema);
‘Student’ — Name for the model, so a collection will be created with a name
‘students’ (plural form of the name with all lowercase)
Now as our model is ready, we can create APIs to get, add, delete, update our
documents within our collection.
Let’s add two documents whenever our app is loaded
const stud = new Student({
roll_no: 1001,
year: 3,
});
By sending an object containing the values to our model Student, we can create a new
document and use save() method to save our document to the cloud.
Now, Let's define a get request for the root route which returns all the documents in
Student collection which should return the document we added.
app.get('/', (req, res) => {
FS QB 77
Student.find({}, (err, found) => {
if (!err) {
res.send(found);
console.log(err);
})
});
render: function () {
return (
<p>{n}</p>
);
}
FS QB 78
render: function () {
return (
<h3>Item {n}</h3>
<p>Description {n}</p>
)
);
}
It should now be clear that the second snippet doesn't really make sense (you can't
return more than one value in JavaScript). You have to either wrap it in another element
(most likely what you'd want, that way you can also provide a valid key
property)
it is possible to return multiple elements by wrapping them within an Array :
render() {
return [
<div><h3>Item {n}</h3></div>
<div><p>Description {n}</p></div>
];
a new feature called React Fragments is introduced which you can use to wrap multiple
elements:
render() {
return (
<React.Fragment key={index}>
<div><h3>Item {n}</h3></div>
<div><p>Description {n}</p></div>
</React.Fragment>
);
}
FS QB 79
npm run dev combines all your JavaScript files into a browser-friendly combined file.
npm run watch does the same, but then it stays active and "watches" for updates to
your .js files. If it detects a change, it'll re-build the browser-friendly file so you can just
refresh the page.
The difference between dev and watch is the dev command will compile the code then
exit while the watch command will compile the components then watch the files and
recompile when one of them changes.
So first, it needs to install Nodejs on our system. NPM will be installed with Nodejs. The
current stable version of Node.js can be downloaded and installed from the official
website that is given below.
https://nodejs.org
Download the latest version and install it. Here we can choose the LTS or the latest
version. Because both of the version supports React.
After the installation, check the versions using the below commands.
node -v
npm -v
After the successful installation of Nodejs and NPM, we can create a new React project
by temporarily installing the create-react-app tool. Execute the below command on the
Command prompt window.
FS QB 80
npx create-react-app awesome-project
Here NPX will temporarily install create-react-app and create a new react project
named awesome-project. Note that the awesome-project is the name I have chosen
for my react project.
So the app we created can run locally on our system with the npm start command.
cd awesome-project
npm start
This will open up the react application in a new tab of our browser with the below URL.
http://localhost:3000
FS QB 81
You’d have noticed that we did not use NavLinks for the filter links.
Try changing these also to NavLinks. What do you observe when
you navigate between the filters? Can you explain this in detail.
The <NavLink> component is similar to the <Link> component, except that several
props can be specified that help you to conditionally add styling attributes to the
rendered element. It accepts the same set of props as the <Link> component (to,
replace, and innerRef) for navigating to a route, and it includes props to style the
selected route.
<NavLink>
A special version of the <Link> that will add styling attributes to the rendered element
when it matches the current URL.
<NavLink to="/about">About</NavLink>
<NavLinkto="/faq"className={isActive =>
"nav-link" + (!isActive ? " unselected" : "")
}>
FAQs
</NavLink>
FS QB 82
The two different pages are shown correctly. Compare this with
the Issue List page, where a componentDidUpdate() method was
needed. Explain in detail why this is so
...
componentDidUpdate(prevProps) {
const oldQuery = prevProps.location.query;
const newQuery = this.props.location.query;
if (oldQuery.status === newQuery.status) {
return;
}
this.loadData();
}
...
IssueList.propTypes = {
location: React.PropTypes.object.isRequired,
};
...
Now, testing will show you that navigating between the filter links indeed reloads the
data.
👆idha padicha onnum puriyathu dhan but ithu dhan answer uuh
FS QB 83
Explain in detail about routing with React routers with the sample
code.
React Router
Routing is a process in which a user is directed to different pages based on their action
or request. ReactJS Router is mainly used for developing Single Page Web
Applications. React Router is used to define multiple routes in the application. When a
user types a specific URL into the browser, and if this URL path matches any 'route'
inside the router file, the user will be redirected to that particular route.
1. react-router: It provides the core routing components and functions for the React
Router applications.
It is not possible to install react-router directly in your application. To use react routing,
first, you need to install react-router-dom modules in your application. The below
command is used to install react router dom.
1. $ npm install react-router-dom --save
Eg:
import React from 'react';
import ReactDOM from 'react-dom';
import { Route, Link, BrowserRouter as Router } from 'react-router-dom'
FS QB 84
import './index.css';
import App from './App';
import About from './about'
import Contact from './contact'
const routing = (
<Router>
<div>
<h1>React Router Example</h1>
<Route path="/" component={App} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</div>
</Router>
ReactDOM.render(routing, document.getElementById('root'));
<html lang="en">
<head>
<title>Hello World</title>
</head>
<body>
<h1 id="msg-box"></h1>
<script>
const scriptURL =
script.src = scriptURL;
FS QB 85
document.head.append(script);
script.onload = ()=>{
};
script.onerror = ()=>{
};
</script>
</body>
</html>
status: "fail"
message: the error message
try {
const savedBook = await newBook.save();
res.status(200).json(savedBook);
res.send("You can now get the requested packages for your request")
} catch (err) {
next(createError(404, "Cannot create book"));
FS QB 86
}
};
router.post('/',createBook);
router.get('/package/:id',getBook);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
FS QB 87
<!-- Coding with nick -->
<title>Quiz App</title>
</head>
<body>
<li>
<input type="radio" name="answer" id="c" class="answer">
<label for="c" id="c_text">Answer</label>
</li>
<li>
<input type="radio" name="answer" id="d" class="answer">
<label for="d" id="d_text">Answer</label>
</li>
</ul>
</div>
<button id="submit">Submit</button>
</div>
<script src="script.js"></script>
</body>
</html>
const quizData = [
{
question: "Which language runs in a web browser?",
a: "Java",
b: "C",
c: "Python",
d: "javascript",
correct: "d",
},
{
question: "What does CSS stand for?",
a: "Central Style Sheets",
FS QB 88
b: "Cascading Style Sheets",
c: "Cascading Simple Sheets",
d: "Cars SUVs Sailboats",
correct: "b",
},
{
question: "What does HTML stand for?",
a: "Hypertext Markup Language",
b: "Hypertext Markdown Language",
c: "Hyperloop Machine Language",
d: "Helicopters Terminals Motorboats Lamborginis",
correct: "a",
},
{
question: "What year was JavaScript launched?",
a: "1996",
b: "1995",
c: "1994",
d: "none of the above",
correct: "b",
},
];
let currentQuiz = 0
let score = 0
loadQuiz()
function loadQuiz() {
deselectAnswers()
questionEl.innerText = currentQuizData.question
a_text.innerText = currentQuizData.a
b_text.innerText = currentQuizData.b
c_text.innerText = currentQuizData.c
d_text.innerText = currentQuizData.d
}
function deselectAnswers() {
FS QB 89
answerEls.forEach(answerEl => answerEl.checked = false)
}
function getSelected() {
let answer
answerEls.forEach(answerEl => {
if (answerEl.checked) {
answer = answerEl.id
}
})
return answer
}
submitBtn.addEventListener('click', () => {
const answer = getSelected()
if (answer) {
if (answer === quizData[currentQuiz].correct) {
score++
}
currentQuiz++
<button onclick="location.reload()">Reload</button>
`
}
}
})
to install nvm on your system is to use the official installer script:
VERSION=v0.37.2
curl -o- "https://raw.githubusercontent.com/nvm-sh/nvm/${VERSION}/install.sh" | bash
FS QB 90
Once nvm
is installed in your system,
One great thing about nvm is that it allows to specify the Node.js version you want to
use for a given project.
For instance, if you are working on a project that requires you to use Node.js 10.10 you
can do the following (in the root folder of the project):
Then every time you work on that project, you only need to run:
nvm use
At this point, you can be sure that you working using the correct Node.js version for your
project.
FS QB 91