{"id":15209104,"url":"https://github.com/amankumarsinhagithub/backend-node-express-ejs-mongodb","last_synced_at":"2025-10-29T13:30:17.481Z","repository":{"id":204463633,"uuid":"711232256","full_name":"AmanKumarSinhaGitHub/Backend-Node-Express-EJS-MongoDB","owner":"AmanKumarSinhaGitHub","description":"🚀 Complete Back-End Guide for Beginners | EJS • NodeJs • ExpressJs • MongoDB  | Become Pro Coder","archived":false,"fork":false,"pushed_at":"2024-05-15T17:17:29.000Z","size":4015,"stargazers_count":34,"open_issues_count":0,"forks_count":2,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-02T01:32:05.792Z","etag":null,"topics":["backend","backend-development","backend-projects","beginner-friendly","crud-app","ejs","expressjs","guide","mern-project","nodejs"],"latest_commit_sha":null,"homepage":"https://aman-kumar-sinha.vercel.app/","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/AmanKumarSinhaGitHub.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-10-28T15:56:51.000Z","updated_at":"2025-01-08T16:28:29.000Z","dependencies_parsed_at":"2024-05-12T07:22:00.699Z","dependency_job_id":"7f229f08-2cc8-4756-9324-72fc8ccf1bb2","html_url":"https://github.com/AmanKumarSinhaGitHub/Backend-Node-Express-EJS-MongoDB","commit_stats":{"total_commits":13,"total_committers":2,"mean_commits":6.5,"dds":"0.15384615384615385","last_synced_commit":"eecbdcf010b9997525507ed8509d8b60f1598182"},"previous_names":["amankumarsinhagithub/backend-node-express-ejs"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AmanKumarSinhaGitHub%2FBackend-Node-Express-EJS-MongoDB","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AmanKumarSinhaGitHub%2FBackend-Node-Express-EJS-MongoDB/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AmanKumarSinhaGitHub%2FBackend-Node-Express-EJS-MongoDB/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AmanKumarSinhaGitHub%2FBackend-Node-Express-EJS-MongoDB/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/AmanKumarSinhaGitHub","download_url":"https://codeload.github.com/AmanKumarSinhaGitHub/Backend-Node-Express-EJS-MongoDB/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":238825791,"owners_count":19537127,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["backend","backend-development","backend-projects","beginner-friendly","crud-app","ejs","expressjs","guide","mern-project","nodejs"],"created_at":"2024-09-28T07:21:22.123Z","updated_at":"2025-10-29T13:30:17.469Z","avatar_url":"https://github.com/AmanKumarSinhaGitHub.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# BackEnd (NodeJs ExpressJs EJS MongoDB)\n\n\n#### 🙏🏻Welcome to our Repository. In this repo, you will **learn A to Z about Backend.**\n\nSteps to setup a backend for any project.\n\n## Express JS Setup\n\n- Use the npm init command to create a package.json file for your application\n    ```\n    npm init \n    ```\n\n- Now install Express\n    ```\n    npm install express\n    ```\n\n\n### Hello World Code in ```app.js``` file\n\n- Visit to [npmjs.com](https://www.npmjs.com/package/express) or [expressjs.com](https://expressjs.com/en/starter/hello-world.html) and Copy the boiler plate (hello world) code\n\n    ```js\n    const express = require('express')\n    const app = express()\n    const port = 3000\n\n    app.get('/', (req, res) =\u003e {\n        res.send('Hello World!')\n    })\n\n    app.listen(port, () =\u003e {\n        console.log(`App listening on port ${port}`)\n    })\n    ```\n\n## EJS setup\n\n- Install [EJS](https://ejs.co/) \n    ```\n    npm install ejs\n    ```\n\n- Set view engine\n    ```js\n    app.set(\"view engine\", \"ejs\") \n    ```\n\n    Now your code look like this\n\n    ```js\n    const express = require('express') \n    const app = express()\n    const port = 3000\n\n    app.set(\"view engine\", \"ejs\")  \n\n    app.get('/', (req, res) =\u003e {\n        res.send('Hello World!')\n    })\n\n    app.listen(port, () =\u003e {\n        console.log(`App listening on port ${port}`)\n    })\n    ```\n- Create ```views``` Folder\n- Create ```ejs``` files inside ```views``` folder\n    - Example - ```index.ejs```\n    - Inside ```index.ejs```, Paste normal html boilder plate code\n\n        ```html\n        \u003c!DOCTYPE html\u003e\n        \u003chtml lang=\"en\"\u003e\n\n        \u003chead\u003e\n            \u003cmeta charset=\"UTF-8\"\u003e\n            \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"\u003e\n            \u003ctitle\u003eIndex.Js File\u003c/title\u003e\n        \u003c/head\u003e\n\n        \u003cbody\u003e\n            \u003ch1\u003eWelcome to Index.Js file (Home Route)\u003c/h1\u003e\n        \u003c/body\u003e\n\n        \u003c/html\u003e\n        ```\n\n\n### Render ```index.ejs``` file inside route\n\n```js\napp.get('/', (req, res) =\u003e {\n    res.render('index')\n})\n```\n\nNow your code (```app.js```) look like this.\n```js\nconst express = require('express') \nconst app = express()\nconst port = 3000\n\napp.set(\"view engine\", \"ejs\") \n\napp.get('/', (req, res) =\u003e {\n    res.render('index')\n})\n\napp.listen(port, () =\u003e {\n    console.log(`App listening on port ${port}`)\n})\n```\n\n### Start the Server\n \nRun this command\n```\nnode app.js\n```\n\nBut, 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.\n\nSo the better approach is to start the server using nodemon\n\n**Install [Nodemon](https://www.npmjs.com/package/nodemon)**\n\n```\nnpm install nodemon\n```\n\nNow to start server, Just type the command given below\n\n```\nnodemon app.js\n```\n\n### Express static files setup\n\n- Create ```public``` Folder\n- Create ```images```, ```stylesheets``` and ```javascripts``` folder inside public folder. \n- You can create files inside these folders. For e.g. ```style.css``` in ```stylesheets``` folder.\n\nNow write this in ```app.js``` file to [serve](https://expressjs.com/en/starter/static-files.html) static files\n\n```js\napp.use(express.static('./public'))\n```\n\nNow your code (```app.js```) look like this\n```js\nconst express = require('express') \nconst app = express()\nconst port = 3000\n\napp.set(\"view engine\", \"ejs\") \napp.use(express.static('./public'))\n\napp.get('/', (req, res) =\u003e {\n    res.render('index')\n})\n\napp.listen(port, () =\u003e {\n    console.log(`App listening on port ${port}`)\n})\n```\nAdding Stylesheet\n```html\n\u003clink rel=\"stylesheet\" href=\"/stylesheets/style.css\"\u003e\n```\n\nNow your ```index.ejs``` file looks like\n\n``` html\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n\n\u003chead\u003e\n    \u003cmeta charset=\"UTF-8\"\u003e\n    \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"\u003e\n    \u003ctitle\u003eIndex.Js File\u003c/title\u003e\n\n    \u003c!-- Linking stylesheet --\u003e\n    \u003clink rel=\"stylesheet\" href=\"/stylesheets/style.css\"\u003e\n    \n\u003c/head\u003e\n\n\u003cbody\u003e\n    \u003ch1\u003eWelcome to Index.Js file (Home Route)\u003c/h1\u003e\n\u003c/body\u003e\n\n\u003c/html\u003e\n```\n\nAnd your directory/folder structure looks like this\n```\n.\n├── app.js\n├── package.json\n├── public\n│   ├── images\n│   ├── javascripts\n│   └── stylesheets\n│       └── style.css\n└── views\n    ├── index.ejs\n\n```\n\n\n# [EXPRESS GENERATOR](https://expressjs.com/en/starter/generator.html)\n\nYou can easily do all the above task by just using express generator and save your time to setting up backend again and again.\n\n#### Install the application generator as a global npm package\n\n```\nnpm install -g express-generator\n```\n\n## Steps to setup\n\nOpen cmd/terminal and type the command below to create an app. \n```\nexpress --view=ejs yourAppName\n```\n\nNow change directory:\n```\ncd yourAppName\n```\n\n\nInstall dependencies:\n```\nnpm install\n```\n\nNow open it on vs code\n```\ncode .\n``` \n\nYour app is created and opened in VS code.\n\n### Run your app by using this command\n\n```\nnpx nodemon\n```\n\n\n#### Note : directory/folder generated by express generator, structure looks like this \n\n```\n.\n├── app.js\n├── bin\n│   └── www\n├── package.json\n├── public\n│   ├── images\n│   ├── javascripts\n│   └── stylesheets\n│       └── style.css\n├── routes\n│   ├── index.js\n│   └── users.js\n└── views\n    ├── error.ejs\n    ├── index.ejs\n    └── layout.ejs\n```\n\n## Some changes that you have to keep in your mind.\n\n1. Previously we write ```app.get```, but now you have to write ```router.get```\n\n2. Previously we start our server using ```npm/npx nodemon yourFileName```, but now we have to write ```npx nodemon``` only.\n\n3. Linking css or other files method remain same.\n\n    ```html\n    \u003clink rel=\"stylesheet\" href=\"/stylesheets/style.css\"\u003e\n    ```\n---\n\n\n# MongoDB\n\nMongoDB is Non-Relational Database.\n\nHere is the table that represent -\u003e If you code then what happen in mongodb\n\n\n| Code Side  |    | MongoDB Side Action Here |\n| -----------|----| ------------------------ |\n| DB Setup   | ⟶ | DB Formation             |\n| Model      | ⟶ | Collection               |\n| Schema     | ⟶ | Documents                |\n\n\n\u003cbr\u003e\n\n### Database Setup == DB Formation\n- All the data of an app == Database\n- And its setup in code side is called DB Setup and in MongoDb side it is called DB formation.\n\n### Model == Collection\nSuppose Amazon have a data base and amazon data base is divided into four parts.\n\n- User DB\n- Sales DB\n- Admin DB\n- Profit DB\n\nThese parts are called MODELS in code side and COLLECTION in MongoDB side.\n\n### Schema == Documents\nLets suppose UserDB have users and user must have their name, address and phone no. \n\nThese are called Schema (in code side) and Documents (in mongo db side)\n\nIn simple work, how each documents of user look like is called schema\n\n\n## Lets set up Data Base\n\nNow we are going to setup a database. To do so, we have to follow these steps.\n\n1. Install [MongoDB Community Edition](https://www.mongodb.com/try/download/community) just like any other application\n\n2. Install Mongoose Js\n\n    ```\n    npm install mongoose\n    ```\n\n3. Require and Setup connection for database\n\n    ```js\n    const mongoose = require(\"mongoose\")\n\n    // Connect to local host mongodb server \n    mongoose.connect(\"mongodb://127.0.0.1:27017/amazonDB\")\n    // The above line create a database in mongodb named \"amazonDB\"\n    ```\n\n4. Make Schema (Document)\n\n    ```js\n    const userSchema = mongoose.Schema({\n        username: String,\n        name: String,\n        age: Number\n    })\n    ```\n\n5. Create Model (collection) and Export\n\n    ```js\n    module.exports = mongoose.model(\"userDB\", userSchema)\n    ```\n\nSo what we did? \n- We created a Database names ```amazonDB```, means Data Setup in code side and DB formation in MongoDB side.\n- We created a model (in code side) or collection (in mongodb side) named ```userDB```. \n- We created a document that contains data format about user, means Schema created in code side named ```userSchema``` and document created in mongodb side.\n\n\n### DATABASE Structure\n\n```\n── amazonDB\n        └── userDB\n                └── userSchema\n```\n\n### Now lets do operations in db\n\nwrite this code in user.js file\n\n```js\nconst mongoose = require(\"mongoose\")\n\n// Connect to local host mongodb server \nmongoose.connect(\"mongodb://127.0.0.1:27017/amazonDB\")\n// The above line create a database in mongodb named \"amazonDB\"\n\nconst userSchema = mongoose.Schema({\n  username: String,\n  name: String,\n  age: Number\n})\n\nmodule.exports = mongoose.model(\"userDB\", userSchema)\n```\n\n\nAnd in index.js to create db\n```js\nvar express = require('express');\nvar router = express.Router();\n\n// Importing mongodb setup code that is written in user.js\nconst userModel = require(\"./users\")\n\n/* GET home page. */\nrouter.get('/', function(req, res, next) {\n  res.render('index');\n});\n\n// Creating model. \nrouter.get(\"/create\", async function (req, res){\n  const createdUser = await userModel.create({\n    // these are schema details\n    username: \"aman\",\n    name: \"aman kumar sinha\",\n    age: 20\n  });\n  res.send(createdUser);\n})\n// Note: all the things related to userModel is asynchronous nodejs function. So always write async and await\n\nmodule.exports = router;\n``` \n\nWhen you visit ```http://localhost:3000/create``` your data base will be created.\n\nTo see the database is created or not. Open terminal. Type command \n```\nmongod\n```\nThis will open your mongodb server.\nThen open a one more tab or a new terminal and type command.\n```\nmongosh\n```\nAnd after that in same terminal type these commands one by one\n```js\n// This command show all the db in your computer\nshow dbs\n\n// Now go to the db that you have created. In our case, its amazonDB\nuse amazonDB\n\n// Now write this command to see all the collection inside amazon db\nshow collections\n\n// Now type this to see what is in userdb collection\ndb.userdbs.find()\n\n// Your userdb's user data look like this\n[\n  {\n    _id: ObjectId(\"65411c6ea1039336d4d364cc\"),\n    username: 'aman',\n    name: 'aman kumar sinha',\n    age: 20,\n    __v: 0\n  }\n]\n```\n\nTo read data using nodejs code (add this line in index.js)\n\n```js\n// See data (READ data)\nrouter.get(\"/allUser\", async function(req, res){\n  let users = await userModel.find()\n  res.send(users)\n})\n\n```\nGo to ```localhost:3000/allUser``` to read data\n\nNote: ```.find()``` return you all the use. ```.findOne()``` return you one user.\n\n```js\nrouter.get(\"/allUser\", async function(req, res){\n  let users = await userModel.findOne({username:\"aman\"})\n  res.send(users)\n})\n```\n\nDelete Data code\n```js\n// DELETE Data\nrouter.get(\"/delete\", async function(req, res){\n  let deletedUser = await userModel.findOneAndDelete({\n    username:\"aman\"\n  })\n  res.send(deletedUser)\n})\n// the above code will find user that username is aman and delete it and return its data to deletedUser variable\n```\n\n### [Session](https://www.npmjs.com/package/express-session) and [cookies](https://www.npmjs.com/package/cookie-parser):\nData that saved on client side is called cookies and the data that saved on server is called session.\n\nTo use session, you need to install a package form npm\n```\nnpm install express-session\n```\n\nIn app.js write some lines to use express-session\n\n```js\nconst session = require('express-session');\n\napp.use(session({\n  secret: 'your-secret-key-here', // A secret key to sign the session ID cookie\n  resave: false, // means if data is not modified, don't resave.\n  saveUninitialized: false // means don't save uninitailized data\n}));\n```\n\nnow you can make/create session (open index.js file)\n\n```js\n// In any route you can set session.\n// 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.\n\nrouter.get('/', function(req, res, next) {\n\n    // Session code here\n    req.session.anyExampleNameHere = 'exampleUserData'; // Storing user data in the session\n\n    res.render('index');\n});\n\n// READ Session\nrouter.get('/checkSession', function(req, res){\n\n    if(req.session.anyExampleNameHere == \"exampleUserData\"){\n        console.log(req.session)\n        res.send(\"Session saved. see on your console/terminal\")\n    }\n    else{\n        res.send(\"Session data is not available or deleted\")\n    }\n    \n})\n```\n\nTo delete session, code is here\n```js\n// Deleting/Destroy session\nrouter.get(\"/removeSession\", function(req, res){\n  req.session.destroy(function(err){\n    if(err) throw err;\n    res.send(\"session deleted\")\n  })\n})\n```\n\n### Cookies-Parser\n\nCookies are already setup in your code by exress generetor, still I am proving the code\n\n```js\nvar cookieParser = require('cookie-parser');\n\napp.use(cookieParser());\n```\n\nCreate and read cookie code (index.js)\n\n```js\nrouter.get('/', function(req, res, next) {\n\n  // Cookies code here\n  res.cookie(\"nameHere\", \"valueHere\")\n\n  res.render('index');\n});\n\n// Read cookie\n\nrouter.get('/checkCookie', function(req, res){\n  console.log(req.cookies)\n  res.send(\"check console/terminal for cookie\")\n})\n\n// Delete cookie\n\nrouter.get('/deleteCookie', function(req, res){\n  res.clearCookie(\"nameHere\")\n  res.send(\"cleared cookie\")\n})\n\n```\n\n## Checkout Our More Branches \n\n- Flash messages\n\n- Intermediate MongoDB\n\n- Authentication and Authorization\n\n- Projects\n\n- And More\n\nCode to see branches\n\n```\ngit branch\n```\n\ncheckout to that branch code\n\n```\ngit checkout \u003cbranch-name\u003e\n```\n\nThank YOU\n\n----\n### Beginner-Friendly Projects with EJS, Node.js, Express.js \u0026 MongoDB\n\nExplore these beginner-friendly projects, featuring authentication and authorization functionalities, built using EJS, Node.js, Express.js, and MongoDB.\n\n#### Projects:\n\n1. **Blog Post Project**\n   - **Features**:\n     - User Authentication: Implement user registration and login seamlessly.\n     - Post Management: Create, edit, and delete posts effortlessly.\n     - User-Centric Viewing: Browse through all posts authored by a specific user.\n     - Profile Enhancement: Upload and update profile images with ease.\n     - Engagement Features: Like and unlike posts to interact with content dynamically.\n   - [GitHub Repository Link](https://github.com/AmanKumarSinhaGitHub/Blog-Post.git)\n  \n2. **To Do App**\n   - [GitHub Repository Link](https://github.com/AmanKumarSinhaGitHub/Backend-Node-Express-EJS-MongoDB)\n   - [Live Demo](https://to-do-list-rz0n.onrender.com/)\n\n\nFeel free to explore and contribute to these projects!\n\n## License\n\nThis project is licensed under the [Creative Commons Attribution-NonCommercial 4.0 International License](https://creativecommons.org/licenses/by-nc/4.0/).\n\n[![License: CC BY-NC 4.0](https://img.shields.io/badge/License-CC%20BY--NC%204.0-lightgrey.svg)](https://creativecommons.org/licenses/by-nc/4.0/)\n\n\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Famankumarsinhagithub%2Fbackend-node-express-ejs-mongodb","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Famankumarsinhagithub%2Fbackend-node-express-ejs-mongodb","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Famankumarsinhagithub%2Fbackend-node-express-ejs-mongodb/lists"}