{"id":18850552,"url":"https://github.com/manthanank/crud-nodejs","last_synced_at":"2026-02-07T21:33:08.600Z","repository":{"id":234236669,"uuid":"788488242","full_name":"manthanank/crud-nodejs","owner":"manthanank","description":"CRUD Nodejs","archived":false,"fork":false,"pushed_at":"2025-01-26T14:33:08.000Z","size":70,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-10-25T04:56:50.761Z","etag":null,"topics":["crud","graphql","mongodb","mysql","nodejs","postgresql"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/manthanank.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","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,"zenodo":null},"funding":{"github":["manthanank"],"open_collective":"manthanank","buy_me_a_coffee":"manthanank","patreon":"manthanank"}},"created_at":"2024-04-18T14:10:00.000Z","updated_at":"2025-07-14T04:23:34.000Z","dependencies_parsed_at":"2024-06-03T20:27:44.525Z","dependency_job_id":"70bae417-c2f3-4416-83e9-ed93a9bd2fa3","html_url":"https://github.com/manthanank/crud-nodejs","commit_stats":null,"previous_names":["manthanank/crud-nodejs"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/manthanank/crud-nodejs","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/manthanank%2Fcrud-nodejs","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/manthanank%2Fcrud-nodejs/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/manthanank%2Fcrud-nodejs/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/manthanank%2Fcrud-nodejs/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/manthanank","download_url":"https://codeload.github.com/manthanank/crud-nodejs/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/manthanank%2Fcrud-nodejs/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29208720,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-07T20:33:12.493Z","status":"ssl_error","status_checked_at":"2026-02-07T20:30:47.381Z","response_time":63,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"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":["crud","graphql","mongodb","mysql","nodejs","postgresql"],"created_at":"2024-11-08T03:29:52.745Z","updated_at":"2026-02-07T21:33:08.579Z","avatar_url":"https://github.com/manthanank.png","language":null,"funding_links":["https://github.com/sponsors/manthanank","https://opencollective.com/manthanank","https://buymeacoffee.com/manthanank","https://patreon.com/manthanank"],"categories":[],"sub_categories":[],"readme":"# CRUD Nodejs\n\n## Table of Contents\n\n1. CRUD Application with Node.js, Express, and MongoDB.\n2. CRUD Application with Node.js, Express, and MySQL.\n\n## CRUD Application with Node.js, Express, and MongoDB\n\n## Project Setup for MySQL\n\n### Step 1: Setting Up the Project\n\nFirst, create a new directory for your project and initialize it with npm:\n\n```bash\nmkdir crud-nodejs\ncd crud-nodejs\nnpm init -y\n```\n\nNext, install the necessary dependencies:\n\n```bash\nnpm install express mongoose cors dotenv body-parser\nnpm install --save-dev nodemon\n```\n\nCreate the following project structure:\n\n```text\ncrud-nodejs\n├── config\n│   └── database.js\n├── controllers\n│   └── todoController.js\n├── middleware\n│   └── errorMiddleware.js\n├── models\n│   └── todo.js\n├── routes\n│   └── todoRoutes.js\n├── .env.example\n├── index.js\n└── package.json\n```\n\n### Step 2: Configuring Environment Variables\n\nCreate a `.env` file (copy from `.env.example`):\n\n```bash\ncp .env.example .env\n```\n\nFill in your MongoDB credentials in the `.env` file:\n\n```js\nPORT=3000\n\nCLIENT_URL=http://localhost:3000\n\nMONGODB_USER=your_mongodb_user\nMONGODB_PASSWORD=your_mongodb_password\nMONGODB_DBNAME=crud\n```\n\n### Step 3: Connecting to MongoDB\n\nIn `config/database.js`, we set up the MongoDB connection using Mongoose:\n\n```js\nconst mongoose = require('mongoose');\n\nrequire('dotenv').config();\n\nconst dbUser = process.env.MONGODB_USER;\nconst dbPassword = process.env.MONGODB_PASSWORD;\nconst dbName = process.env.MONGODB_DBNAME || 'crud';\n\nconst mongoURI = `mongodb+srv://${dbUser}:${dbPassword}@cluster0.re3ha3x.mongodb.net/${dbName}?retryWrites=true\u0026w=majority`;\n\nmodule.exports = async function connectDB() {\n    try {\n        await mongoose.connect(mongoURI, {\n            useNewUrlParser: true, useUnifiedTopology: true\n        });\n        console.log('MongoDB connected');\n    } catch (error) {\n        console.error('MongoDB connection failed');\n        console.error(error);\n    }\n};\n```\n\n### Step 4: Creating the Express Server\n\nIn `index.js`, we configure the Express server and connect to MongoDB:\n\n```js\nconst express = require(\"express\");\nconst bodyParser = require(\"body-parser\");\nconst helmet = require(\"helmet\");\nconst morgan = require(\"morgan\");\nconst cors = require(\"cors\");\nconst todoRoutes = require(\"./routes/todoRoutes\");\nconst errorMiddleware = require(\"./middleware/errorMiddleware\");\n\nrequire(\"dotenv\").config();\n\nconst app = express();\nconst PORT = process.env.PORT || 3000;\n\n// Middleware\napp.use(bodyParser.json());\napp.use(helmet());\napp.use(morgan(\"common\"));\napp.use(cors());\n\n// Routes\napp.use(\"/todos\", todoRoutes);\n\n// Error middleware\napp.use(errorMiddleware);\n\n// Start the server\napp.listen(PORT, () =\u003e {\n  console.log(`Server is running on http://localhost:${PORT}`);\n});\n```\n\n### Step 5: Defining the Todo Model\n\nIn `models/todo.js`, we define the Todo schema using Mongoose:\n\n```js\nconst mongoose = require('mongoose');\n\nconst todoSchema = new mongoose.Schema({\n    title: {\n        type: String,\n        required: true\n    },\n    completed: {\n        type: Boolean,\n        default: false\n    }\n});\n\nmodule.exports = mongoose.model('Todo', todoSchema);\n```\n\n### Step 6: Creating the Controller\n\nIn `controllers/todoController.js`, we define the logic for handling CRUD operations:\n\n```js\nconst Todo = require('../models/todo');\nconst { validateTodo } = require('../utils/validationUtils');\n\nexports.createTodo = async (req, res) =\u003e {\n    const todo = req.body;\n\n    if (!validateTodo(todo)) {\n        return res.status(400).json({ message: 'Invalid todo object' });\n    }\n\n    try {\n        const newTodo = new Todo(todo);\n        await newTodo.save();\n        res.status(201).json({ message: 'Todo created successfully' });\n    } catch (error) {\n        res.status(500).json({ message: error.message });\n    }\n};\n\nexports.getAllTodos = async (req, res) =\u003e {\n    try {\n        const todos = await Todo.find();\n        res.send(todos);\n    } catch (err) {\n        res.status(500).send(err);\n    }\n};\n\nexports.getTodoById = async (req, res) =\u003e {\n    try {\n        const todo = await Todo.findById(req.params.id);\n        if (!todo) return res.status(404).send('Todo not found');\n        res.send(todo);\n    } catch (err) {\n        res.status(500).send(err);\n    }\n};\n\nexports.updateTodo = async (req, res) =\u003e {\n    try {\n        const todo = await Todo.findByIdAndUpdate(req.params.id, req.body, { new: true });\n        if (!todo) return res.status(404).send('Todo not found');\n        res.status(200).send({ message: 'Todo updated successfully'});\n    } catch (err) {\n        res.status(400).send(err);\n    }\n};\n\nexports.deleteTodo = async (req, res) =\u003e {\n    try {\n        const todo = await Todo.findByIdAndDelete(req.params.id);\n        if (!todo) return res.status(404).send('Todo not found');\n        res.status(200).json({ message: 'Todo deleted successfully' });\n    } catch (err) {\n        res.status(500).send(err);\n    }\n};\n```\n\n### Step 7: Defining Routes\n\nIn `routes/todoRoutes.js`, we set up the routes for the Todo API:\n\n```js\nconst express = require('express');\nconst router = express.Router();\nconst todoController = require('../controllers/todoController');\n\n// Routes\nrouter.post('/', todoController.createTodo);\nrouter.get('/', todoController.getAllTodos);\nrouter.get('/:id', todoController.getTodoById);\nrouter.patch('/:id', todoController.updateTodo);\nrouter.delete('/:id', todoController.deleteTodo);\n\nmodule.exports = router;\n```\n\n### Step 8: Error Handling Middleware\n\nIn `middleware/errorMiddleware.js`, we define a simple error handling middleware:\n\n```js\n// middleware/errorMiddleware.js\nmodule.exports = function errorHandler(err, req, res, next) {\n    console.error(err.stack);\n    res.status(500).send('Something broke!');\n};\n```\n\n### Step 9: Running the Application\n\nAdd the following scripts to `package.json`:\n\n```js\n{\n  \"name\": \"crud-nodejs\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" \u0026\u0026 exit 1\",\n    \"dev\": \"nodemon index.js\",\n    \"start\": \"node index.js\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/manthanank/crud-nodejs.git\"\n  },\n  \"keywords\": [],\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"bugs\": {\n    \"url\": \"https://github.com/manthanank/crud-nodejs/issues\"\n  },\n  \"homepage\": \"https://github.com/manthanank/crud-nodejs#readme\",\n  \"dependencies\": {\n    \"body-parser\": \"^1.20.2\",\n    \"cors\": \"^2.8.5\",\n    \"dotenv\": \"^16.4.5\",\n    \"express\": \"^4.19.2\",\n    \"mongoose\": \"^8.3.2\",\n    \"nodemon\": \"^3.1.0\"\n  }\n}\n```\n\nStart the application in development mode:\n\n```bash\nnpm run dev\n```\n\n## CRUD Application with Node.js, Express, and MySQL\n\n## Project Setup for MongoDB\n\n### Step 1: Initializing the Project\n\nCreate a new directory for your project and initialize it with npm:\n\n```bash\nmkdir crud-nodejs\ncd crud-nodejs\nnpm init -y\n```\n\nInstall the necessary dependencies:\n\n```bash\nnpm install express mysql2 dotenv body-parser\nnpm install --save-dev nodemon\n```\n\n### Step 2: Project Structure\n\nCreate the following project structure:\n\n```text\ncrud-nodejs\n├── config\n│   └── database.js\n├── controllers\n│   └── todoController.js\n├── middleware\n│   └── errorMiddleware.js\n├── models\n│   └── todo.js\n├── routes\n│   └── todoRoutes.js\n├── .env.example\n├── index.js\n└── package.json\n```\n\n### Step 3: Configuring Environment Variables\n\nCreate a `.env` file (copy from `.env\n\n.example`):\n\n```bash\ncp .env.example .env\n```\n\nFill in your MySQL database credentials in the `.env` file:\n\n```js\nPORT=3000\nDB_HOST=localhost\nDB_USER=your_user\nDB_PASSWORD=your_password\nDB_DATABASE=your_database\n```\n\n### Step 4: Connecting to MySQL\n\nIn `config/database.js`, we set up the MySQL connection using the `mysql2` package:\n\n```js\nconst mysql = require('mysql2');\n\nrequire('dotenv').config();\n\nconst connection = mysql.createConnection({\n    host: process.env.DB_HOST,\n    user: process.env.DB_USER,\n    password: process.env.DB_PASSWORD,\n    database: process.env.DB_DATABASE\n});\n\nconnection.connect((err) =\u003e {\n    if (err) throw err;\n    console.log('Connected to MySQL database');\n});\n\nmodule.exports = connection;\n```\n\n### Step 5: Creating the Express Server\n\nIn `index.js`, we configure the Express server and set up the routes and error handling middleware:\n\n```js\nconst express = require('express');\nconst cors = require(\"cors\");\nconst bodyParser = require('body-parser');\nconst helmet = require('helmet');\nconst morgan = require('morgan');\nconst connectDB = require('./config/database');\nconst todoRoutes = require('./routes/todoRoutes');\nconst errorMiddleware = require('./middleware/errorMiddleware');\n\nrequire('dotenv').config();\n\nconst app = express();\nconst PORT = process.env.PORT || 3000;\n\napp.use(\n    cors({\n        origin: \"*\",\n    })\n);\napp.use(helmet());\napp.use(morgan('common'));\n\n// Middleware\napp.use(bodyParser.json());\n\n// Connect to MongoDB\nconnectDB();\n\n// Routes\napp.use('/todos', todoRoutes);\n\n// Error middleware\napp.use(errorMiddleware);\n\n// Start the server\napp.listen(PORT, () =\u003e {\n    console.log(`Server started on port ${PORT}`);\n});\n```\n\n### Step 6: Defining the Todo Model\n\nIn `models/todo.js`, we define the functions to interact with the MySQL database:\n\n```js\nconst db = require('../config/database');\n\nexports.getAllTodos = function(callback) {\n    db.query('SELECT * FROM todos', callback);\n};\n\nexports.getTodoById = function(id, callback) {\n    db.query('SELECT * FROM todos WHERE id = ?', [id], callback);\n};\n\nexports.createTodo = function(newTodo, callback) {\n    db.query('INSERT INTO todos SET ?', newTodo, callback);\n};\n\nexports.updateTodo = function(id, updatedTodo, callback) {\n    db.query('UPDATE todos SET ? WHERE id = ?', [updatedTodo, id], callback);\n};\n\nexports.deleteTodo = function(id, callback) {\n    db.query('DELETE FROM todos WHERE id = ?', [id], callback);\n};\n```\n\n### Step 7: Creating the Controller\n\nIn `controllers/todoController.js`, we define the logic for handling CRUD operations:\n\n```js\nconst Todo = require('../models/todo');\n\nexports.getAllTodos = function(req, res) {\n    Todo.getAllTodos((err, todos) =\u003e {\n        if (err) throw err;\n        res.json(todos);\n    });\n};\n\nexports.getTodoById = function(req, res) {\n    Todo.getTodoById(req.params.id, (err, todo) =\u003e {\n        if (err) throw err;\n        res.json(todo);\n    });\n};\n\nexports.createTodo = function(req, res) {\n    const newTodo = {\n        title: req.body.title,\n        completed: req.body.completed\n    };\n\n    Todo.createTodo(newTodo, (err, result) =\u003e {\n        if (err) throw err;\n        res.json({ message: 'Todo created successfully'});\n    });\n};\n\nexports.updateTodo = function(req, res) {\n    const updatedTodo = {\n        title: req.body.title,\n        completed: req.body.completed\n    };\n\n    Todo.updateTodo(req.params.id, updatedTodo, (err, result) =\u003e {\n        if (err) throw err;\n        res.json({ message: 'Todo updated successfully' });\n    });\n};\n\nexports.deleteTodo = function(req, res) {\n    Todo.deleteTodo(req.params.id, (err, result) =\u003e {\n        if (err) throw err;\n        res.json({ message: 'Todo deleted successfully' });\n    });\n};\n```\n\n### Step 8: Defining Routes\n\nIn `routes/todoRoutes.js`, we set up the routes for the Todo API:\n\n```js\nconst express = require('express');\nconst router = express.Router();\nconst todoController = require('../controllers/todoController');\n\n// Routes\nrouter.get('/', todoController.getAllTodos);\nrouter.get('/:id', todoController.getTodoById);\nrouter.post('/', todoController.createTodo);\nrouter.put('/:id', todoController.updateTodo);\nrouter.delete('/:id', todoController.deleteTodo);\n\nmodule.exports = router;\n```\n\n### Step 9: Error Handling Middleware\n\nIn `middleware/errorMiddleware.js`, we define a simple error handling middleware:\n\n```js\nmodule.exports = function errorHandler(err, req, res, next) {\n    console.error(err.stack);\n    res.status(500).send('Something broke!');\n};\n```\n\n### Step 10: Running the Application\n\nAdd the following scripts to `package.json`:\n\n```js\n{\n  \"name\": \"crud-nodejs\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" \u0026\u0026 exit 1\",\n    \"dev\": \"nodemon index.js\",\n    \"start\": \"node index.js\"\n  },\n  \"keywords\": [],\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"body-parser\": \"^1.20.2\",\n    \"dotenv\": \"^16.4.5\",\n    \"express\": \"^4.19.2\",\n    \"mysql2\": \"^3.9.7\",\n    \"nodemon\": \"^3.1.0\"\n  }\n}\n```\n\nStart the application in development mode:\n\n```bash\nnpm run dev\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmanthanank%2Fcrud-nodejs","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmanthanank%2Fcrud-nodejs","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmanthanank%2Fcrud-nodejs/lists"}