- Notifications
You must be signed in to change notification settings - Fork2
🚀 Complete Back-End Guide for Beginners | EJS • NodeJs • ExpressJs • MongoDB | Become Pro Coder
License
AmanKumarSinhaGitHub/Backend-Node-Express-EJS-MongoDB
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Steps to setup a backend for any project.
Use the npm init command to create a package.json file for your application
npm initNow install Express
npm install express
Visit tonpmjs.com orexpressjs.com and Copy the boiler plate (hello world) code
constexpress=require('express')constapp=express()constport=3000app.get('/',(req,res)=>{res.send('Hello World!')})app.listen(port,()=>{console.log(`App listening on port${port}`)})
InstallEJS
npm install ejsSet view engine
app.set("view engine","ejs")
Now your code look like this
constexpress=require('express')constapp=express()constport=3000app.set("view engine","ejs")app.get('/',(req,res)=>{res.send('Hello World!')})app.listen(port,()=>{console.log(`App listening on port${port}`)})
Create
viewsFolderCreate
ejsfiles insideviewsfolderExample -
index.ejsInside
index.ejs, Paste normal html boilder plate code<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Index.Js File</title></head><body><h1>Welcome to Index.Js file (Home Route)</h1></body></html>
app.get('/',(req,res)=>{res.render('index')})
Now your code (app.js) look like this.
constexpress=require('express')constapp=express()constport=3000app.set("view engine","ejs")app.get('/',(req,res)=>{res.render('index')})app.listen(port,()=>{console.log(`App listening on port${port}`)})
Run this command
node app.jsBut, there is a problem in this way. Whenever you made some changes in your file, you have to restart the server again and again to reflect the changes.
So the better approach is to start the server using nodemon
InstallNodemon
npm install nodemonNow to start server, Just type the command given below
nodemon app.js- Create
publicFolder - Create
images,stylesheetsandjavascriptsfolder inside public folder. - You can create files inside these folders. For e.g.
style.cssinstylesheetsfolder.
Now write this inapp.js file toserve static files
app.use(express.static('./public'))
Now your code (app.js) look like this
constexpress=require('express')constapp=express()constport=3000app.set("view engine","ejs")app.use(express.static('./public'))app.get('/',(req,res)=>{res.render('index')})app.listen(port,()=>{console.log(`App listening on port${port}`)})
Adding Stylesheet
<linkrel="stylesheet"href="/stylesheets/style.css">
Now yourindex.ejs file looks like
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Index.Js File</title><!-- Linking stylesheet --><linkrel="stylesheet"href="/stylesheets/style.css"></head><body><h1>Welcome to Index.Js file (Home Route)</h1></body></html>
And your directory/folder structure looks like this
.├── app.js├── package.json├── public│ ├── images│ ├── javascripts│ └── stylesheets│ └── style.css└── views ├── index.ejsYou can easily do all the above task by just using express generator and save your time to setting up backend again and again.
npm install -g express-generatorOpen cmd/terminal and type the command below to create an app.
express --view=ejs yourAppNameNow change directory:
cd yourAppNameInstall dependencies:
npm installNow open it on vs code
code .Your app is created and opened in VS code.
npx nodemon.├── app.js├── bin│ └── www├── package.json├── public│ ├── images│ ├── javascripts│ └── stylesheets│ └── style.css├── routes│ ├── index.js│ └── users.js└── views ├── error.ejs ├── index.ejs └── layout.ejsPreviously we write
app.get, but now you have to writerouter.getPreviously we start our server using
npm/npx nodemon yourFileName, but now we have to writenpx nodemononly.Linking css or other files method remain same.
<linkrel="stylesheet"href="/stylesheets/style.css">
MongoDB is Non-Relational Database.
Here is the table that represent -> If you code then what happen in mongodb
| Code Side | MongoDB Side Action Here | |
|---|---|---|
| DB Setup | ⟶ | DB Formation |
| Model | ⟶ | Collection |
| Schema | ⟶ | Documents |
- All the data of an app == Database
- And its setup in code side is called DB Setup and in MongoDb side it is called DB formation.
Suppose Amazon have a data base and amazon data base is divided into four parts.
- User DB
- Sales DB
- Admin DB
- Profit DB
These parts are called MODELS in code side and COLLECTION in MongoDB side.
Lets suppose UserDB have users and user must have their name, address and phone no.
These are called Schema (in code side) and Documents (in mongo db side)
In simple work, how each documents of user look like is called schema
Now we are going to setup a database. To do so, we have to follow these steps.
InstallMongoDB Community Edition just like any other application
Install Mongoose Js
npm install mongooseRequire and Setup connection for database
constmongoose=require("mongoose")// Connect to local host mongodb servermongoose.connect("mongodb://127.0.0.1:27017/amazonDB")// The above line create a database in mongodb named "amazonDB"
Make Schema (Document)
constuserSchema=mongoose.Schema({username:String,name:String,age:Number})
Create Model (collection) and Export
module.exports=mongoose.model("userDB",userSchema)
So what we did?
- We created a Database names
amazonDB, means Data Setup in code side and DB formation in MongoDB side. - We created a model (in code side) or collection (in mongodb side) named
userDB. - We created a document that contains data format about user, means Schema created in code side named
userSchemaand document created in mongodb side.
── amazonDB └── userDB └── userSchemawrite this code in user.js file
constmongoose=require("mongoose")// Connect to local host mongodb servermongoose.connect("mongodb://127.0.0.1:27017/amazonDB")// The above line create a database in mongodb named "amazonDB"constuserSchema=mongoose.Schema({username:String,name:String,age:Number})module.exports=mongoose.model("userDB",userSchema)
And in index.js to create db
varexpress=require('express');varrouter=express.Router();// Importing mongodb setup code that is written in user.jsconstuserModel=require("./users")/* GET home page. */router.get('/',function(req,res,next){res.render('index');});// Creating model.router.get("/create",asyncfunction(req,res){constcreatedUser=awaituserModel.create({// these are schema detailsusername:"aman",name:"aman kumar sinha",age:20});res.send(createdUser);})// Note: all the things related to userModel is asynchronous nodejs function. So always write async and awaitmodule.exports=router;
When you visithttp://localhost:3000/create your data base will be created.
To see the database is created or not. Open terminal. Type command
mongodThis will open your mongodb server.Then open a one more tab or a new terminal and type command.
mongoshAnd after that in same terminal type these commands one by one
// This command show all the db in your computershowdbs// Now go to the db that you have created. In our case, its amazonDBuseamazonDB// Now write this command to see all the collection inside amazon dbshowcollections// Now type this to see what is in userdb collectiondb.userdbs.find()// Your userdb's user data look like this[{_id:ObjectId("65411c6ea1039336d4d364cc"),username:'aman',name:'aman kumar sinha',age:20,__v:0}]
To read data using nodejs code (add this line in index.js)
// See data (READ data)router.get("/allUser",asyncfunction(req,res){letusers=awaituserModel.find()res.send(users)})
Go tolocalhost:3000/allUser to read data
Note:.find() return you all the use..findOne() return you one user.
router.get("/allUser",asyncfunction(req,res){letusers=awaituserModel.findOne({username:"aman"})res.send(users)})
Delete Data code
// DELETE Datarouter.get("/delete",asyncfunction(req,res){letdeletedUser=awaituserModel.findOneAndDelete({username:"aman"})res.send(deletedUser)})// the above code will find user that username is aman and delete it and return its data to deletedUser variable
Data that saved on client side is called cookies and the data that saved on server is called session.
To use session, you need to install a package form npm
npm install express-sessionIn app.js write some lines to use express-session
constsession=require('express-session');app.use(session({secret:'your-secret-key-here',// A secret key to sign the session ID cookieresave:false,// means if data is not modified, don't resave.saveUninitialized:false// means don't save uninitailized data}));
now you can make/create session (open index.js file)
// In any route you can set session.// in our session session is set in home route and if someone visit our home route, session will create and if you open checkSession route, you can see session.router.get('/',function(req,res,next){// Session code herereq.session.anyExampleNameHere='exampleUserData';// Storing user data in the sessionres.render('index');});// READ Sessionrouter.get('/checkSession',function(req,res){if(req.session.anyExampleNameHere=="exampleUserData"){console.log(req.session)res.send("Session saved. see on your console/terminal")}else{res.send("Session data is not available or deleted")}})
To delete session, code is here
// Deleting/Destroy sessionrouter.get("/removeSession",function(req,res){req.session.destroy(function(err){if(err)throwerr;res.send("session deleted")})})
Cookies are already setup in your code by exress generetor, still I am proving the code
varcookieParser=require('cookie-parser');app.use(cookieParser());
Create and read cookie code (index.js)
router.get('/',function(req,res,next){// Cookies code hereres.cookie("nameHere","valueHere")res.render('index');});// Read cookierouter.get('/checkCookie',function(req,res){console.log(req.cookies)res.send("check console/terminal for cookie")})// Delete cookierouter.get('/deleteCookie',function(req,res){res.clearCookie("nameHere")res.send("cleared cookie")})
Flash messages
Intermediate MongoDB
Authentication and Authorization
Projects
And More
Code to see branches
git branchcheckout to that branch code
git checkout <branch-name>Thank YOU
Explore these beginner-friendly projects, featuring authentication and authorization functionalities, built using EJS, Node.js, Express.js, and MongoDB.
Blog Post Project
- Features:
- User Authentication: Implement user registration and login seamlessly.
- Post Management: Create, edit, and delete posts effortlessly.
- User-Centric Viewing: Browse through all posts authored by a specific user.
- Profile Enhancement: Upload and update profile images with ease.
- Engagement Features: Like and unlike posts to interact with content dynamically.
- GitHub Repository Link
- Features:
To Do App
Feel free to explore and contribute to these projects!
This project is licensed under theCreative Commons Attribution-NonCommercial 4.0 International License.
About
🚀 Complete Back-End Guide for Beginners | EJS • NodeJs • ExpressJs • MongoDB | Become Pro Coder
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Uh oh!
There was an error while loading.Please reload this page.