nodejs
nodejs
What is Nodejs
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine.
Node.js allows you to run JavaScript on the server.
Node.js also provides library of various JavaScript modules which helps to develop web
applications.
Node.js was developed by Ryan Dahl in 2009.
Node js is not a language or a framework.
Advantages of NodeJS
● Open Source
● Efficient, Fast and Highly Scalable
● Event Driven
● Very Popular
Prerequisite
● JavaScript
● NPM
REPL
The repl module provides a Read-Eval-Print-Loop (REPL) implementation that is available both
as a standalone program or includible in other applications.
JavaScript Expression
Variable
Global and Local Scope
_ (underscore) Variable
Function
Some Commands
.break Sometimes you get stuck, this gets you out
.clear Alias for .break
.editor Enter editor mode (Ctrl+D to finish, Ctrl+C to cancel).
.exit Exit the REPL
.help Print this help message
.load Load JS from a file into the REPL session e.g. .load ./file/to/load.js
.save Save all evaluated commands in this REPL session to a file e.g. .save ./file/to/save.js
Press Ctrl+C to abort current expression, Ctrl+D to exit the REPL
Run in Node JS
index.js
console.log(“Hello Sonam”)
node index.js
Module Wrapper
Before a module's code is executed, Node.js will wrap it with a function wrapper that looks like
the following:
(function(exports, require, module, __filename, __dirname) {
// Module code actually lives in here
});
By doing this, Node.js achieves a few things:
•It keeps top-level variables (defined with var, const or let) scoped to the module rather than the
global object.
•It helps to provide some global-looking variables that are actually specific to the module, such
as:
•The module and exports objects that the implementor can use to export values from the
module.
•The convenience variables __filename and __dirname, containing the module's absolute
filename and directory path.
exports – A reference to the module.exports that is shorter to type.
require – Used to import modules.
module – A reference to the current module.
__dirname – The directory name of the current module. This is the same as the path.dirname()
of the __filename.
Example:- console.log(__dirname);
__filename – The file name of the current module. This is the current module file's absolute path
with symlinks resolved.
Example:- console.log(__filename);
Path
The path module provides utilities for working with file and directory paths. It can be accessed
using:
const path = require('path’);
basename() – The basename() method returns the last portion of a path, similar to the Unix
basename command. Trailing directory separators are ignored.
Syntax:- basename(path[, ext])
Example:- basename(‘/test/something.html’, ‘.html’);
dirname() – The dirname() method returns the directory name of a path, similar to the Unix
dirname command. Trailing directory separators are ignored.
Syntax:- dirname(path)
Example:- dirname(‘/test/something.html’);
extname() - The extname() method returns the extension of the path, from the last occurrence of
the . (period) character to end of string in the last portion of the path. If there is no . in the last
portion of the path, or if there are no . characters other than the first character of the basename
of path, an empty string is returned.
Syntax:- extname(path)
Example:- extname('index.html’);
join() – The join() method joins all given path segments together using the platform-specific
separator as a delimiter, then normalizes the resulting path.
Zero-length path segments are ignored. If the joined path string is a zero-length string then '.'
will be returned, representing the current working directory.
Syntax:- join([…paths])
Example:- join('/search', 'label', 'course/python', 'oop', '..');
normalize() – The normalize() method normalizes the given path, resolving '..' and '.' segments.
If the path is a zero-length string, '.' is returned, representing the current working directory.
Syntax:- normalize(path)
Example:-
normalize('C:\\temp\\\\foo\\bar\\..\\’);
win32.normalize('C:////temp\\\\/\\/\\/foo/bar’);
Note - win32 property provides access to Windows-specific implementations of the path
methods.
parse() – The parse() method returns an object whose properties represent significant elements
of the path. Trailing directory separators are ignored.
Syntax:- parse(path)
Example:- parse('C:\\path\\dir\\file.txt');
isAbsolute() – The path.isAbsolute() method determines if path is an absolute path. If the given
path is a zero-length string, false will be returned.
Syntax:- isAbsolute(path)
Example:-
isAbsolute('//server'); // true
isAbsolute('\\\\server'); // true
isAbsolute('C:/foo/..'); // true
isAbsolute('C:\\foo\\..'); // true
isAbsolute('bar\\baz'); // false
isAbsolute('bar/baz'); // false
isAbsolute('.'); // false
File System
The fs module enables interacting with the file system in a way modeled on standard POSIX
functions.
Promise Based API
•const fs = require('fs/promises’);
•import * as fs from 'fs/promises';
Callback API
•const fs = require('fs’);
•import * as fs from 'fs';
Sync API
•const fs = require('fs’);
•import * as fs from 'fs';
Promise API
The fs/promises API provides asynchronous file system methods that return promises.
mkdir() – Asynchronously creates a directory.
Syntax:- mkdir(path[, options])
readdir() – Reads the contents of a directory.
Syntax:- readdir(path[, options])
rmdir() – Removes the directory identified by path.
Syntax:- rmdir(path[, options])
writeFile() – Asynchronously writes data to a file, replacing the file if it already exists.
Syntax:- writeFile(file, data[, options])
readFile() – Asynchronously reads the entire contents of a file.
Syntax:- readFile(path[, options])
appendFile(path, data[, options]) – Asynchronously append data to a file, creating the file if it
does not yet exist.
Syntax:- appendFile(path, data[, options])
copyFile() – Asynchronously copies src to dest. By default, dest is overwritten if it already exists.
Syntax:- copyFile(src, dest[, mode])
stat() – Used to get file information.
Syntax:- stat(path[, options])
Callback API
The callback APIs perform all operations asynchronously, without blocking the event loop, then
invoke a callback function upon completion or error.
mkdir() – Asynchronously creates a directory.
Syntax:- mkdir(path[, options], callback)
readdir() – Reads the contents of a directory.
Syntax:- readdir(path[, options], callback)
rmdir() – Removes the directory identified by path.
Syntax:- rmdir(path[, options], callback)
writeFile() – Asynchronously writes data to a file, replacing the file if it already exists.
Syntax:- writeFile(file, data[, options], callback)
readFile() – Asynchronously reads the entire contents of a file.
Syntax:- readFile(path[, options], callback)
appendFile(path, data[, options]) – Asynchronously append data to a file, creating the file if it
does not yet exist.
Syntax:- appendFile(path, data[, options], callback)
copyFile() – Asynchronously copies src to dest. By default, dest is overwritten if it already exists.
Syntax:- copyFile(src, dest[, mode], callback)
stat() – Used to get file information.
Syntax:- stat(path[, options], callback)
Synchronous API
The synchronous APIs perform all operations synchronously, blocking the event loop until the
operation completes or fails.
mkdirSync() – Synchronously creates a directory.
Syntax:- mkdirSync(path[, options])
readdirSync() – Reads the contents of a directory.
Syntax:- readdirSync(path[, options])
rmdirSync() – Removes the directory identified by path.
Syntax:- rmdirSync(path[, options])
writeFileSync() – Synchronously writes data to a file, replacing the file if it already exists.
Syntax:- writeFileSync(file, data[, options])
readFileSync() – Synchronously reads the entire contents of a file.
Syntax:- readFileSync(path[, options])
appendFileSync(path, data[, options]) – Synchronously append data to a file, creating the file if it
does not yet exist.
Syntax:- appendFileSync(path, data[, options])
copyFileSync() – Synchronously copies src to dest. By default, dest is overwritten if it already
exists.
Syntax:- copyFileSync(src, dest[, mode])
statSync() – Used to get file information.
Syntax:- statSync(path[, options])
OS
The os module provides operating system-related utility methods and properties.
const os = require('os’);
import * as os from ‘os’;
platform() – Returns a string identifying the operating system platform. The value is set at
compile time. Possible values are 'aix', 'darwin', 'freebsd', 'linux', 'openbsd', 'sunos', and 'win32'.
arch() – Returns the operating system CPU architecture for which the Node.js binary was
compiled. Possible values are 'arm', 'arm64', 'ia32', 'mips', 'mipsel', 'ppc', 'ppc64', 's390', 's390x',
'x32', and 'x64’.
cpus() – Returns an array of objects containing information about each logical CPU core.
hostname() – Returns the host name of the operating system as a string.
homedir() – Returns the string path of the current user's home directory.
networkInterfaces() - Returns an object containing network interfaces that have been assigned a
network address.
freemem() – Returns the amount of free system memory in bytes as an integer.
totalmem() – Returns the total amount of system memory in bytes as an integer.
URL
The url module provides utilities for URL resolution and parsing.
const url = require(‘url’);
import url from ‘url’;
const myURL = new URL('https://www.example.com:8080/p/a/t/h?query=string#hash’);
hash – Gets and sets the fragment portion of the URL.
host – Gets and sets the host portion of the URL.
hostname – Gets and sets the host name portion of the URL. The key difference between
url.host and url.hostname is that url.hostname does not include the port.
href – Gets and sets the serialized URL.
pathname – Gets and sets the path portion of the URL.
port – Gets and sets the port portion of the URL.
protocol – Gets and sets the protocol portion of the URL.
search – Gets and sets the serialized query portion of the URL.
toString() – The toString() method on the URL object returns the serialized URL. The value
returned is equivalent to that of url.href and url.toJSON().
toJSON() – The toJSON() method on the URL object returns the serialized URL. The value
returned is equivalent to that of url.href and url.toString().
Event
const EventEmitter = require('events’);
import EventEmitter from ‘events’;
on – When a listener is registered using the on() method, that listener is invoked every time the
named event is emitted. on() method is used to register listeners.
Syntax:- on(eventName, callback)
once - When a listener is registered using the once() method, it is possible to register a listener
that is called at most once for a particular event. Once the event is emitted, the listener is
unregistered and then called.
Syntax:- once(eventName, callback)
emit() – The emit() method allows an arbitrary set of arguments to be passed to the listener
functions. emit() method is used to trigger the event.
Syntax:- emit(eventName, args)
HTTP
The HTTP interfaces in Node.js are designed to support many features of the protocol which
have been traditionally difficult to use.
const http = require(‘http’);
import http from ‘http’;
createServer([options][, requestListener]) – Returns a new instance of http.Server.
DNS
The HTTP interfaces in Node.js are designed to support many features of the protocol which
have been traditionally difficult to use.
const http = require(‘http’);
import http from ‘http’;
createServer([options][, requestListener]) – Returns a new instance of http.Server.
Introduction to Express JS
Express Js is Fast, unopinionated, minimalist web framework for Node.js.
● Create Static, Dynamic and Hybrid Web App
● Fast and Easy
● Routing
● Middleware
● REST API
● Very Popular
Prerequisite
● HTML
● CSS
● JavaScript
● NPM
● Node JS
● Bootstrap
● Tailwind CSS
● Axios
● Fetch API
● Node JS
● NPM
● Install Express JS
npm install express
npm install [email protected]
● Uninstall Express JS
npm uninstall express
npm uninstall [email protected]
● Install Nodemon
npm install nodemon
Babel
Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards
compatible version of JavaScript in current and older browsers or environments. Here are the
main things Babel can do for you:
● Transform syntax
● Polyfill features that are missing in your target environment
● Source code transformations
@babel/core – This is the main package to run any babel setup or configuration.
@babel/cli – Babel comes with a built-in CLI which can be used to compile files from the
command line.
@babel/node – This is a CLI that works exactly the same as the Node.js CLI, with the added
benefit of compiling with Babel presets and plugins before running it.
@babel/preset-env – This enables us to use new and upcoming features which node.js is yet to
understand. New features are always new and will probably take time to implement in NodeJS
by default.
npm install –D @babel/core @babel/cli @babel/node @babel/preset-env
Babel CLI
Compile Files:
● npx babel index.js – It complies index.js file.
● npx babel index.js --out-file index-compiled.js – It compiles index.js file and output to a
file index-compiled.js. We can use --out-file or -o
● npx babel index.js --watch --out-file index-compiled.js – It complies index.js every time
we make changes and output to a file index-compiled.js. We can use --watch or -w
Compile Directory:
● npx babel src --out-dir prd – It compiles the entire src directory and output it to the prd
directory by using either --out-dir or -d. This doesn't overwrite any other files or
directories in prd.
● npx babel src --out-file index-compiled.js – It compiles the entire src directory and output
it as a single concatenated file.
Setup Babel
Use the application generator tool, express-generator, to quickly create an application skeleton.
npx express-generator --view=ejs myapp
npm install -g express-generator
express --view=ejs myapp
npm install
set DEBUG=myapp:* & npm start
● myapp – Application/Project Folder
● bin – The bin folder contains the executable file that starts your app. It starts the server
(on port 3000, if no alternative is supplied) and sets up some basic error handling.
● public – Everythingin this folder is accessible to people connecting to application. We
can put JavaScript, CSS, images, and other assets.
● routes – We can put all our route files. The generator creates two files, index.js and
users.js.
● views – The views folder is where we have files used by your templating engine.
● app.js File – This file creates an express application object (named app, by convention),
sets up the application with various settings and middleware, and then exports the app
from the module.
express() – The express() function is a top-level function exported by the express module.
const app = express()
The app returned by express() is in fact a JavaScript Function, designed to be passed to Node’s
HTTP servers as a callback to handle requests.
This makes it easy to provide both HTTP and HTTPS versions of your app with the same code
base, as the app does not inherit from these.
app.listen() – It binds and listens for connections on the specified host and port.
If port is omitted or is 0, the operating system will assign an arbitrary unused port, which is
useful for cases like automated tasks.
Routing
Routing refers to determining how an application responds to a client request to a particular
endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so
on).
Each route can have one or more callback functions, which are executed when the route is
matched.
Syntax:- app.method(path, callback)
app.method(path, [callback1, callback2, ….])
app.method(path, [callback1, callback2, ….], callback)
● app is an instance of express.
● method is an HTTP request method, in lowercase.
● path is a path on the server.
● callback is the function executed when the route is matched.
app.js
// All Student Routes // All Teacher Routes
Router
Router class is used to create modular, mountable route handlers.
A Router instance is a complete middleware and routing system.
Every Express application has a built-in app router.
Steps:-
res.send(‘Hello World’)
})
•Export router
module.exports = router
routes/teachers.js
routes/students.js
const router = express.Router() const router = express.Router()
// All Teacher Routes
// All Student Routes
router.get(‘/teacher/all', (req, res) =>{
router.get(‘/student/all', (req, res) =>{
res.send(‘All Student’) }) res.send(‘All Teachers’) })
/student/all
app.js /student/create
const student = require(‘./students’) /student/update
/student/delete
const teacher = require(‘./teachers’)
/teacher/all
app.use(‘/student’, student)
/teacher/create
app.use(‘/teacher’, teacher) /teacher/update
/teacher/delete
Route Parameter
Route parameters are named URL segments that are used to capture the values specified at
their position in the URL.
The captured values are populated in the req.params object, with the name of the route
parameter specified in the path as their respective keys.
The name of route parameters must be made up of “word characters” ([A-Za-z0-9_]).
Examples:-
/student/:id // www.example.com/student/12
/product/:category/:id // www.example.com/product/mobile/23
/product/order/:year/and/:month // www.example.com/order/2021/and/oct
/train/:from-:to // www.example.com/train/ranchi-dhanbad
/location/:state.:city // www.example.com/location/jh.ranchi
req.params = {“state” : “jh”, “city”: “ranchi”}
Route Parameter
app.param() – The app.param() function is used to add the callback triggers to route
parameters. It is commonly used to check for the existence of the data requested related to the
route parameter.
All param callbacks will be called before any handler of any route in which the param occurs,
and they will each be called only once in a request-response cycle, even if the parameter is
matched in multiple routes.
Syntax:-
app.param(name, callback)
app.param([name1, name2,….], callback)
If name is an array, the callback trigger is registered for each parameter declared in it, in the
order in which they are declared.
Query String
/product // www.example.com/product?category=mobile
req.query = {“category” : “mobile”}
/product // www.example.com/product?category=mobile&id=13
req.query = {“category” : “mobile”, “id”:13}
Controller
Controllers can group related request handling logic separately. Instead of defining all of your
request handling logic as callback in route or route files, you may wish to organize this behavior
using Controller modules.
app.js
app.get(‘/student/all', (req, res) =>{
res.send(‘All Student’)
})
routes/student.js
router.get(‘/all', (req, res) =>{
res.send(‘All Student’)
})
controllers/studentController.js
app.js const allStudent = (req, res) =>{
app.get(‘/student/all', (req, res) =>{ res.send(‘All Student’)
}
res.send(‘All Student’) export { allStudent }
module.export = { allStudent }
})
app.get(‘/student/all’, allStudent)
routes/student.js
router.get(‘/all', (req, res) =>{
res.send(‘All Student’)
})
router.get(‘/all’, allStudent)
View
Views contain the HTML served by your application and separate your application logic from
your presentation logic. Views are stored in the views directory.
Creating View
views/index.html
<html>
<body>
<h1>Hello Home Page</h1>
</body>
</html>
Example:-
app.get(‘/’, (req, res) => {
res.sendFile(join(process.cwd(), 'views', 'index.html’))
});
process.cwd() – process is node's global object, and .cwd() returns where node is running.
app.sendFile() – This is used to transfers the file at the given path. Sets the Content-Type
response HTTP header field based on the filename’s extension. Unless the root option is set in
the options object, path must be an absolute path to the file.
Static Files
CSS files, Javascript Files, image files, video files etc are considered as static files in Express
JS.
To serve static files such as images, CSS files, and JavaScript files, use the express.static
built-in middleware function in Express.
Syntax:- express.static(root, [options])
Example:- app.use(express.static('public’))
http://localhost:3000/css/style.css
To create a virtual path prefix (where the path does not actually exist in the file system) for files
that are served by the express.static function, specify a mount path for the static directory, as
shown below:
app.use('/static', express.static('public’))
http://localhost:3000/static/css/style.css
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:
app.use('/static', express.static(join(process.cwd(), 'public')))
const options = {
dotfiles: 'ignore’,
etag: false,
extensions: ['htm', 'html'],
index: false,
maxAge: '1d',
redirect: false,
setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now())
}}
app.use(express.static('public', options))
dotfiles
“allow” - No special treatment for dotfiles.
“deny” - Deny a request for a dotfile, respond with 403, then call next().
“ignore” - Act as if the dotfile does not exist, respond with 404, then call next().
NOTE: With the default value, it will not ignore files in a directory that begins with a dot.
Template Engine
A template engine enables you to use static template files in your application.
At runtime, the template engine replaces variables in a template file with actual values, and
transforms the template into an HTML file sent to the client.
This approach makes it easier to design an HTML page.
● Ejs
● Pug
● Mustache
● Nunjucks
● Dust
https://expressjs.com/en/resources/template-engines.html
•Install Template Engine
npm install ejs
app.js
•Setup the Directory where template files are located
app.set('views', './views’)
•Setup the Template Engine to use
app.set('view engine', ‘ejs')
app.js
app.get('/', function (req, res) { •If the view engine property is not set, you
res.render('index') must specify the extension of the view file.
})
routes/web.js app.set('view engine', ‘ejs’)
router.get('/', function (req, res) { router.get('/', function (req, res) {
res.render('index’)
}) res.render('index.ejs’)
router.get(‘/about', function (req, res) {
res.render(‘about’) })
})
•When you make a request to the home
page, the index.ejs file will be rendered as
HTML.
render
res.render( ) – It renders a view and sends the rendered HTML string to the client.
Syntax:- res.render(view [, locals] [, callback])
view – The view argument is a string that is the file path of the view file to render.
This can be an absolute path, or a path relative to the views setting.
If the path does not contain a file extension, then the view engine setting determines the file
extension.
locals – It’s an object whose properties define local variables for the view.
callback – It’s a function. If provided, the method returns both the possible error and rendered
string, but does not perform an automated response. When an error occurs, the method invokes
next(err) internally.
EJS (Embedded JavaScript) is a simple templating language that lets you generate HTML
markup with plain JavaScript.
● Fast compilation and rendering
● Simple template tags: <% %>
● Custom delimiters (e.g., use [? ?] instead of <% %>)
● Sub-template includes
● Ships with CLI
● Both server JS and browser support
● Static caching of intermediate JavaScript
● Static caching of templates
● Complies with the Express view system
Displaying Data - You may display data that is passed to your views by wrapping the variable in
<%= %>
Example:- <%= name %>
Comment – EJS also allows you to define comments in your views. However, unlike HTML
comments, EJS comments are not included in the HTML returned by your application.
<%# This comment will not be present in the rendered HTML %>
If
If evaluates a variable, and if that variable is “true” (i.e. exists, is not empty, and is not a false
boolean value).
Syntax:-
<% if (variable) { %>
…………..
<% } %>
Example:-
<% if name %>
</h1>Hello <%= name %></h1>
<% } %>
Conditional
•if.. else..
…………
…………
<% } %>
Loop
while
•for <% while (condition) { %>
……………………
<% for (initial; condition; incr/decr ) { %> <% } %>
……………………
<% } %>
Function Call
include – Include are relative to the template with the include call.
Syntax:-
<%- include(filename, object) %>
<%- include(folder/filename, object) %>
Example:-
<%- include(‘footer’,{name: ‘Sonam’}) %>
<%- include(‘myfolder/footer’, {name: ‘Sonam’}) %>
Geeky Steps
These below steps are common steps which you will follow in almost every project.
● Create Project New Folder
● Change Directory to Express Project – cd geekyshows
● Create app.js file inside Project Folder
● Create package.json file – npm init –y
● Install Express JS – npm i express
● Install Nodemon – npm i nodemon
● Install ejs – npm i ejs
● Install any other packages if required
● Create controllers folder – All business logic code & files will be inside this folder
● Create routes folder – All routes files will be inside this folder
● Create views folder – All presentational files will be inside this folder
Middleware
Middleware functions are functions that have access to the request object (req), the response
object (res), and the next function in the application’s request-response cycle.
The next function is a function in the Express router which, when invoked, executes the
middleware succeeding the current middleware.
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 in the stack.
Creating Middleware
middlewares/logger-middleware.js
app.js var myLogger = function (req, res, next) {
console.log(‘Logged’)
app.use(function (req, res, next) { next()
console.log(‘Logged’) }
app.js
next() import myLogger from
‘./middlewares/logger-middleware.js’
}) app.use(myLogger)
routes/student.js
console.log(‘Logger’)
next()
})
Using 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.
A middleware function with no mount path. The function is executed every time the app receives
a request.
app.use(function (req, res, next) {
app.use(function (req, res, next) { console.log(‘Logged 1’)
next()
console.log(‘Logged’) }, function (req, res, next) {
next() console.log(‘Logged 2’)
}) next()
})
Application Level Middleware
middlewares/logger-middleware.js
var myLogger = function (req, res, next) {
console.log(‘Logged’)
next()
}
app.js
import myLogger from ‘./middlewares/logger-middleware.js’
app.use(myLogger)
A Middleware function mounted on the /about path. The function is executed for any type of
HTTP request on the /about path.
middlewares/logger-middleware.js
var myLogger = function (req, res, next) {
console.log(‘Logged’)
next()
}
app.js
import myLogger from ‘./middlewares/logger-middleware.js’
app.use(‘/about', myLogger)
Router Level Middleware
middlewares/logger-middleware.js
var myLogger = function (req, res, next) {
console.log(‘Logged’)
next()
}
routes/web.js
import myLogger from ‘./middlewares/logger-middleware.js’
router.use(myLogger)
A Middleware function mounted on the /student path. The function is executed for any type of
HTTP request on the /student path.
Built-in Middleware
•express.static serves static assets such as HTML files, images, and so on.
•express.json parses incoming requests with JSON payloads.
•express.urlencoded parses incoming requests with URL-encoded payloads.
MongoDB is a document database designed for ease of development and scaling. It is one of
the most powerful NoSQL system and database. Being a NoSQL means that it does not use the
usual rows and columns. This database uses a document storage format called BSON which is
a binary style of JSON documents.
Example:-
{
_id: ObjectId(“6abs665jhsj7”),
name: “Sonam”,
age: 27,
hobbies: [‘Dancing’, ‘Reading’],
city: “Ranchi”,
islogin: true
}
Locally Hosted Deployments
• MongoDB Community
• MongoDB Enterprise Advance
Cloud Hosted Deployment
•MongoDB Atlas
mongo – mongo is the command-line shell that connects to a specific instance of mongod.
When you run mongo with no parameters it defaults to connecting to the localhost on port
27017.
mongod – mongod is the primary daemon process for the MongoDB system. It handles data
requests, manages data access, and performs background management operations.
mongos – For a sharded cluster, the mongos instances provide the interface between the client
applications and the sharded cluster. The mongos instances route queries and write operations
to the shards. From the perspective of the application, a mongos instance behaves identically to
any other MongoDB instance.
mongosh – The MongoDB Shell, mongosh, is a fully functional JavaScript and Node.js 14.x
REPL environment for interacting with MongoDB deployments. You can use the MongoDB Shell
to test queries and operations directly with your database.
MongoDB provides the db.createCollection() method to explicitly create a collection with various
options, such as setting the maximum size or the documentation validation rules.
db.createCollection(“student”, {
validator:{
$jsonSchema:{
bsonType: “object”,
required: [“name”, “age”],
properties:{
name:{ bsonType: “String”, description: “Must be a String and is required”},
age: { bsonType: “int”, description: “Must be a Integer and is required”},
}
}
}
})
Show Collection List – show collections is used to List Collections.
Show Validation Rules – db.getCollectionInfos( { name: “Collection_name" } ) is used to show
validation rule of specific collection.
Drop Collection – db.COLLECTION_NAME.drop() is used to Delete Collection.
Retrieve All Document – db.COLLECTION_NAME.find().pretty() is used to retrieve document.
Insert Single Data – db.COLLECTION_NAME.insetOne({name: “Sonam”, age: 27})
Insert Multiple Data – db.COLLECTION_NAME.insetMany([{name: “Sumit”, age: 22}, {name:
“Kunal”, age:45}])
Retrieve One Document – db.COLLECTION_NAME.findOne() is used to retrieve one document.
Limit Retrieved Document – db.COLLECTION_NAME.find().limit(NUMBER)
Retrieve Document based on field – db.COLLECTION_NAME.find({name: “Sonam”}).pretty()
Update Single Document – db.COLLECTION_NAME.updateOne(<filter>, update)
db.student.updateOne({age:27}, {$set: {name: “Jack”} })
Update Multiple Document – db.COLLECTION_NAME.updateMany(<filter>, update)
db.student.updateMany({age:27}, {$set: {name: “Jack”} })
Delete Single Document – db.COLLECTION_NAME.deleteOne(filter)
db.student.deleteOne({age:27})
Delete Multiple Document – db.COLLECTION_NAME.deleteMany(filter)
db.student.deleteMany({age:27})
Introduction to Mongoose
Mongoose provides a straight-forward, schema-based solution to model your application data. It
includes built-in type casting, validation, query building, business logic hooks and more, out of
the box.
Requirements
● Node
● MongoDB
How to install Mongoose
npm i mongoose
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
user: 'geekyshows',
pass: 'merapassword',
dbName: 'schooldb',
authSource: 'schooldb'
}
mongoose.connect("mongodb://localhost:27017", options);
Schema
A document schema is a JSON object that allows you to define the shape and content of
documents and embedded documents in a collection. You can use a schema to require a
specific set of fields, configure the content of a field, or to validate changes to a document
based on its beginning and ending states.
Defining Schema
Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection
and defines the shape of the documents within that collection.
By default, Mongoose adds an _id property to your schemas.
Syntax:-
import mongoose from 'mongoose’
const nameSchema = new mongoose.Schema({
key1: String, // String is shorthand for {type: String}
key2: Number,
key3: mongoose.Decimal128,
key4: [String],
key5: Boolean,
key6: [{ key: String, key: Date }],
key7: Date
})
Syntax:-
import mongoose from 'mongoose’
const nameSchema = new mongoose.Schema({
key1: {type:String},
key2: {type:Number},
key3: {type:mongoose.Decimal128},
key4: {type:Array},
key5: {type:Boolean},
key6: [{ key: {type:String}, key: {type:Date} }],
key7: {type:Date}
})
Example:-
import mongoose from 'mongoose’
const studentSchema = new mongoose.Schema({
name: {type:String},
age: {type:Number},
fees: {type:mongoose.Decimal128},
hobbies: {type:Array},
isactive: {type:Boolean},
comments: [{ value: {type:String}, publish: {type:Date} }],
join: {type:Date}
})
_id Property
When you create a new document with the automatically added _id property, Mongoose creates
a new _id of type ObjectId to your document.
ObjectIds encode the local time at which they were created. That means you can usually pull
the time that a document was created from its _id.
You can also overwrite Mongoose's default _id with your own _id.
Mongoose will refuse to save a document that doesn't have an _id, so you're responsible for
setting _id if you define your own _id path.
Type
•String
•Number
•Date
•Buffer
•Boolean
•Mixed
•ObjectId
•Array
•Decimal128
•Map
const clothSchema = new mongoose.Schema({
bottomwear:{
type:String
price:Number
}
})
const clothSchema = new mongoose.Schema({
bottomwear:{
type:{type:String}
price:Number
}
})
String
lowercase: boolean, whether to always call .toLowerCase() on the value
uppercase: boolean, whether to always call .toUpperCase() on the value
trim: boolean, whether to always call .trim() on the value
match: RegExp, creates a validator that checks if the value matches the given regular
expression
enum: Array, creates a validator that checks if the value is in the given array.
minLength: Number, creates a validator that checks if the value length is not less than the given
number
maxLength: Number, creates a validator that checks if the value length is not greater than the
given number
populate: Object, sets default populate options
Number
min: Number, creates a validator that checks if the value is greater than or equal to the given
minimum.
max: Number, creates a validator that checks if the value is less than or equal to the given
maximum.
enum: Array, creates a validator that checks if the value is strictly equal to one of the values in
the given array.
populate: Object, sets default populate options
Date
min: Date
max: Date
Boolean
Mongoose casts the below values to true:
true
'true'
1
'1'
'yes’
Mongoose casts the below values to false:
false
'false'
0
'0'
'no'
Defining Schema
Example:-
import mongoose from 'mongoose’
const studentSchema = new mongoose.Schema({
name: {type:String, required:true},
age: { type: Number, min: 18, max: 65 },
fees: {type:mongoose.Decimal128, validate: v => v >= 5500.50},
hobbies: {type:Array},
isactive: {type:Boolean},
comments: [{ value: {type:String}, publish: {type:Date} }],
join: { type: Date, default: Date.now },
})
schema.path ( )
The schema.path() function returns the instantiated schema type for a given path.
Example:- studentSchema.path(‘age’)
Model
Models are fancy constructors compiled from Schema definitions. An instance of a model is
called a document. Models are responsible for creating and reading documents from the
underlying MongoDB database.
Compiling Schema
const studentSchema = mongoose.schema({})
const studentModel = mongoose.model(‘Student’, studentSchema);
The first argument is the singular name of the collection your model is for. Mongoose
automatically looks for the plural, lowercased version of your model name. Thus, for the
example above, the model Student is for the students collection in the database.
Create Document
// Defining Schema
const studentSchema = mongoose.schema({name:String})
// Compiling Schema
const StudentModel = mongoose.model(‘Student’, studentSchema);
// Creating New Document
const studentDoc = new StudentModel ({
name: ‘Sonam’
})
// Saving Document
await studentDoc.save()
save() – It is used to save document by inserting a new document into the database if
document.isNew is true, or sends an updateOne operation only with the modifications to the
database, it does not replace the whole document in the latter case.
It returns undefined if used with callback or a Promise otherwise.
Example:-
})
Retrieve Document
Update Document
Each model has its own update method for modifying documents in the database without
returning them to your application.
findByIdAndUpdate() – It finds a matching document, updates it according to the update arg,
passing any options, and returns the found document (if any) to the callback. The query
executes if callback is passed.
Syntax:- findByIdAndUpdate(id, update, options, callback)
id can be object, number or string.
Example:- findByIdAndUpdate(“324ff2dsfsd323”, {name: “Sunil”}, {returnDocument: after})
Example:- findByIdAndUpdate(“324ff2dsfsd323”, { $set: {name: “Sunil”} } , {returnDocument:
after})
updateOne () – It is used to update single document. MongoDB will update only the first
document that matches filter regardless of the value of the multi option.
Syntax:- updateOne(filter, update, options, callback)
Example:- updateOne({_id: “324ff2dsfsd323”}, {name: “Sunil”}, {upsert: true})
upsert – If true, and no documents found, insert a new document.
updateMany () – It is used to update multiple document. MongoDB will update all documents
that match filter regardless of the value of the multi option.
Syntax:- updateMany(filter, update, options, callback)
Example:- updateMany({age: 27}, {name: “Sunil”}, {upsert: true})
Delete Document
deleteMany() – It is used to delete multiple document. MongoDB will delete all documents that
match conditions.
Syntax:- deleteMany(conditions, options, callback)
Example:- deleteMany({age: 27})
Example:- deleteMany({name: “Sonam”, age: 27})
urlencoded()
res.redirect([status,] path) – It redirects to the URL derived from the specified path, with
specified status, a positive integer that corresponds to an HTTP status code . If not specified,
status defaults to “302 “Found”.
res.redirect(‘/student/success')
res.redirect('http://example.com')
res.redirect(301, 'http://example.com')
res.redirect('../login')
Cookie-parser
cookie-parser is a middleware which parses cookies attached to the client request object.
Parse Cookie header and populate req.cookies with an object keyed by the cookie names.
npm i cookie-parser
import cookieParser from 'cookie-parser’
// var cookieParser = require('cookie-parser’)
app.use(cookieParser())
res.cookie( )
res.cookie () – It is used to set cookie name to value. The value parameter may be a string or
object converted to JSON.
Syntax:- res.cookie(name, value [, options])
Example:-
res.cookie("username", "geekyshows")
res.cookie(“cart", 5)
res.cookie(“cart”, { items: [1, 2, 3] })
res.cookie("username", "geekyshows", {maxAge: 5000})
res.cookie("username", "geekyshows", {expires: new Date(Date.now() + 900000), httpOnly:
true})
res.cookie("username", "geekyshows", {path: ‘/admin’})
res.cookie( )
Property Type Description
domain String Domain name for the cookie. Defaults to the domain name of
the app.
expires Date Expiry date of the cookie in GMT. If not specified or set to 0,
creates a session cookie.
httpOnly Boolean Flags the cookie to be accessible only by the web server.
maxAge Number Convenient option for setting the expiry time relative to the
current time in milliseconds.
res.clearCookie( )
res.clearCookie () – It is used to Clears the cookie specified by name.
Web browsers and other compliant clients will only clear the cookie if the given options is
identical to those given to res.cookie(), excluding expires and maxAge.
Syntax:- res.clearCookie(name [, options])
Example:-
res.clearCookie("username")
res.cookie("username", “geekyshows”, { path: '/admin' })
res.clearCookie("username",{ path: '/admin' })
Express-session
npm i express-session
import session from ‘express-session’
// var session = require(‘express-session’)
app.use(session({
secret: ‘iamkey',
resave: false,
saveUninitialized: true,
cookie: {path: '/', httpOnly: true, secure: false, maxAge: 5000 }
}))
secret – This is the secret used to sign the session ID cookie. This can be either a string for a
single secret, or an array of multiple secrets. If an array of secrets is provided, only the first
element will be used to sign the session ID cookie, while all the elements will be considered
when verifying the signature in requests. The secret itself should be not easily parsed by a
human and would best be a random set of characters.
resave – It forces the session to be saved back to the session store, even if the session was
never modified during the request. True If it does not implement the touch method and your
store sets an expiration date on stored sessions. False If it implements the touch method.
saveUninitialized – It forces a session that is "uninitialized" to be saved to the store. A session is
uninitialized when it is new but not modified. Choosing false is useful for implementing login
sessions, reducing server storage usage, or complying with laws that require permission before
setting a cookie. Choosing false will also help with race conditions where a client makes multiple
parallel requests without a session.
cookie – Settings object for the session ID cookie.
name – The name of the session ID cookie to set in the response. The default value is
'connect.sid’.
proxy – Trust the reverse proxy when setting secure cookies.
true The "X-Forwarded-Proto" header will be used.
false All headers are ignored and the connection is considered secure only if there is a direct
TLS/SSL connection.
undefined Uses the "trust proxy" setting from express. It is default.
store – The session store instance, defaults to a new MemoryStore instance.
Req.session
To store or access session data, simply use the request property req.session, which is
(generally) serialized as JSON by the store, so nested objects are typically fine.
Example:-
req.session.count = 1
req.session.count
req.session.regenerate() - To regenerate the session simply invoke the method. Once complete,
a new SID and Session instance will be initialized at req.session and the callback will be
invoked.
req.session.destroy(callback) – It destroys the session and will unset the req.session property.
Once complete, the callback will be invoked.
req.session.reload(callback) – It reloads the session data from the store and re-populates the
req.session object. Once complete, the callback will be invoked.
req.session.id - Each session has a unique ID associated with it. This property is an alias of
req.sessionID and cannot be modified. It has been added to make the session ID accessible
from the session object.
req.session.cookie - Each session has a unique cookie object accompany it. This allows you to
alter the session cookie per visitor. For example we can set req.session.cookie.expires to false
to enable the cookie to remain for only the duration of the user-agent.
cookie.maxAge - Alternatively req.session.cookie.maxAge will return the time remaining in
milliseconds, which we may also re-assign a new value to adjust the .expires property
appropriately.
Cookie.originalMaxAge - The req.session.cookie.originalMaxAge property returns the original
maxAge (time-to-live), in milliseconds, of the session cookie.
req.sessionID - To get the ID of the loaded session, access the request property req.sessionID.
This is simply a read-only value set when a session is loaded/created.
Readme.txt
npm init -y
npm i express
npm i -D nodemon
npm i ejs
npm i mongoose
npm i express-session
npm i express-flash
npm i connect-mongo
npm i bcrypt
//////////////////////////////////////////////////////
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.cs
s">
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-sm-4" style="background-color:lavender;">
<form method="post">
<div class="form-group">
<label for="email">Name:</label>
<input type="text" class="form-control" id="name">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>
<a href="" cass="btn btn-primary btn-lg"><i class="fa fa-pencil"></i></a>
<a href="" cass="btn btn-danger btn-lg"><i class="fa fa-trash"></i></a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
========================================================================
===============================
//email.js
import nodemailer from 'nodemailer'
// create reusable transporter object using the default SMTP transport
const transporter = nodemailer.createTransport({
port: 465, // true for 465, false for other ports
host: "smtp.gmail.com",
auth: {
user: '[email protected]',
pass: 'nvpfrreijgbekrfu',
},
secure: true,
});
===============step 2
import transporter from "../email.js";
static sendemail = async (req, res) => {
const {email, details} = req.body
const mailData = {
from: '[email protected]', // sender address
to: '[email protected]', // list of receivers
subject: email,
text: details,
// html: '',
attachments: [
{
filename: 'readme.txt',
// path: 'C://Users/akshay/Desktop/expressjs/'
},
],
};
res.send("email sent")