Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

🚀 Complete Back-End Guide for Beginners | EJS • NodeJs • ExpressJs • MongoDB | Become Pro Coder

License

NotificationsYou must be signed in to change notification settings

AmanKumarSinhaGitHub/Backend-Node-Express-EJS-MongoDB

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🙏🏻Welcome to our Repository. In this repo, you willlearn A to Z about Backend.

Steps to setup a backend for any project.

Express JS Setup

  • Use the npm init command to create a package.json file for your application

    npm init
  • Now install Express

    npm install express

Hello World Code inapp.js file

  • 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}`)})

EJS setup

  • InstallEJS

    npm install ejs
  • Set 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}`)})
  • Createviews Folder

  • Createejs files insideviews folder

    • Example -index.ejs

    • Insideindex.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>

Renderindex.ejs file inside route

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}`)})

Start the Server

Run this command

node app.js

But, 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 nodemon

Now to start server, Just type the command given below

nodemon app.js

Express static files setup

  • Createpublic Folder
  • Createimages,stylesheets andjavascripts folder inside public folder.
  • You can create files inside these folders. For e.g.style.css instylesheets folder.

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.ejs

You can easily do all the above task by just using express generator and save your time to setting up backend again and again.

Install the application generator as a global npm package

npm install -g express-generator

Steps to setup

Open cmd/terminal and type the command below to create an app.

express --view=ejs yourAppName

Now change directory:

cd yourAppName

Install dependencies:

npm install

Now open it on vs code

code .

Your app is created and opened in VS code.

Run your app by using this command

npx nodemon

Note : directory/folder generated by express generator, structure looks like this

.├── app.js├── bin│   └── www├── package.json├── public│   ├── images│   ├── javascripts│   └── stylesheets│       └── style.css├── routes│   ├── index.js│   └── users.js└── views    ├── error.ejs    ├── index.ejs    └── layout.ejs

Some changes that you have to keep in your mind.

  1. Previously we writeapp.get, but now you have to writerouter.get

  2. Previously we start our server usingnpm/npx nodemon yourFileName, but now we have to writenpx nodemon only.

  3. Linking css or other files method remain same.

    <linkrel="stylesheet"href="/stylesheets/style.css">

MongoDB

MongoDB is Non-Relational Database.

Here is the table that represent -> If you code then what happen in mongodb

Code SideMongoDB Side Action Here
DB SetupDB Formation
ModelCollection
SchemaDocuments

Database Setup == DB Formation

  • 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.

Model == Collection

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.

Schema == Documents

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

Lets set up Data Base

Now we are going to setup a database. To do so, we have to follow these steps.

  1. InstallMongoDB Community Edition just like any other application

  2. Install Mongoose Js

    npm install mongoose
  3. Require 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"
  4. Make Schema (Document)

    constuserSchema=mongoose.Schema({username:String,name:String,age:Number})
  5. Create Model (collection) and Export

    module.exports=mongoose.model("userDB",userSchema)

So what we did?

  • We created a Database namesamazonDB, means Data Setup in code side and DB formation in MongoDB side.
  • We created a model (in code side) or collection (in mongodb side) nameduserDB.
  • We created a document that contains data format about user, means Schema created in code side nameduserSchema and document created in mongodb side.

DATABASE Structure

── amazonDB        └── userDB                └── userSchema

Now lets do operations in db

write 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

mongod

This will open your mongodb server.Then open a one more tab or a new terminal and type command.

mongosh

And 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-session

In 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-Parser

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

Checkout Our More Branches

  • Flash messages

  • Intermediate MongoDB

  • Authentication and Authorization

  • Projects

  • And More

Code to see branches

git branch

checkout to that branch code

git checkout <branch-name>

Thank YOU


Beginner-Friendly Projects with EJS, Node.js, Express.js & MongoDB

Explore these beginner-friendly projects, featuring authentication and authorization functionalities, built using EJS, Node.js, Express.js, and MongoDB.

Projects:

  1. 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
  2. To Do App

Feel free to explore and contribute to these projects!

License

This project is licensed under theCreative Commons Attribution-NonCommercial 4.0 International License.

License: CC BY-NC 4.0

About

🚀 Complete Back-End Guide for Beginners | EJS • NodeJs • ExpressJs • MongoDB | Become Pro Coder

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp