{"id":21965357,"url":"https://github.com/techsolutionstuff/how-to-create-rest-api-using-node-js-and-mongodb","last_synced_at":"2026-04-05T22:37:10.720Z","repository":{"id":224298372,"uuid":"762942744","full_name":"Techsolutionstuff/how-to-create-rest-api-using-node-js-and-mongodb","owner":"Techsolutionstuff","description":"Welcome to my article on creating a RESTful API using Node.js and MongoDB.","archived":false,"fork":false,"pushed_at":"2024-02-25T05:58:07.000Z","size":4,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-07-30T13:07:28.265Z","etag":null,"topics":["body-parser","crud-operation","express-js","mongodb","mongoose","node-js","nodejs","nodejs-api","nodejs-crud","rest-api","restful-api"],"latest_commit_sha":null,"homepage":"https://techsolutionstuff.com/post/how-to-create-rest-api-using-node-js-and-mongodb","language":null,"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/Techsolutionstuff.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":"2024-02-25T05:56:14.000Z","updated_at":"2024-04-08T15:46:48.000Z","dependencies_parsed_at":null,"dependency_job_id":"a63ba19a-8c54-4622-8912-f0837168e963","html_url":"https://github.com/Techsolutionstuff/how-to-create-rest-api-using-node-js-and-mongodb","commit_stats":null,"previous_names":["techsolutionstuff/how-to-create-rest-api-using-node-js-and-mongodb"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Techsolutionstuff/how-to-create-rest-api-using-node-js-and-mongodb","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Techsolutionstuff%2Fhow-to-create-rest-api-using-node-js-and-mongodb","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Techsolutionstuff%2Fhow-to-create-rest-api-using-node-js-and-mongodb/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Techsolutionstuff%2Fhow-to-create-rest-api-using-node-js-and-mongodb/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Techsolutionstuff%2Fhow-to-create-rest-api-using-node-js-and-mongodb/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Techsolutionstuff","download_url":"https://codeload.github.com/Techsolutionstuff/how-to-create-rest-api-using-node-js-and-mongodb/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Techsolutionstuff%2Fhow-to-create-rest-api-using-node-js-and-mongodb/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31452899,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-05T21:22:52.476Z","status":"ssl_error","status_checked_at":"2026-04-05T21:22:51.943Z","response_time":75,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6: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":["body-parser","crud-operation","express-js","mongodb","mongoose","node-js","nodejs","nodejs-api","nodejs-crud","rest-api","restful-api"],"created_at":"2024-11-29T12:39:25.245Z","updated_at":"2026-04-05T22:37:09.983Z","avatar_url":"https://github.com/Techsolutionstuff.png","language":null,"readme":"# How to Create REST API using Node.js and MongoDB\n\n\u003cp\u003eHey there! Welcome to my article on creating a RESTful API using Node.js and MongoDB. If you\u0026#39;re looking to build powerful and scalable web applications, understanding how to create a robust API is essential.\u003c/p\u003e\n\n\u003cp\u003eIn this guide, I\u0026#39;ll walk you through the process of building a REST API step by step using express.js and mongoDB.\u003c/p\u003e\n\n\u003cp\u003eA REST API utilizes various HTTP methods to perform operations on resources. It typically employs a GET request to retrieve a record, a POST request to create one, a PUT request to update a record, and a DELETE request to delete one.\u003c/p\u003e\n\n\u003cp\u003eThese HTTP methods provide a standardized way for clients to interact with the server and perform CRUD (Create, Read, Update, Delete) operations on resources.\u003c/p\u003e\n\n\u003cp\u003eSo, let\u0026#39;s see how to create a REST API using node js and MongoDB, express.js, and MongoDB rest API, how to create a rest API with node js and express, and how to create REST API in node.js.\u003c/p\u003e\n\n\u003cdiv style=\"background:#eeeeee;border:1px solid #cccccc;padding:5px 10px;\"\u003e\u003cstrong\u003eStep 1: Setup Development Environment\u003c/strong\u003e\u003c/div\u003e\n\n\u003cp\u003eEnsure Node.js is installed on your machine. You can download it from the official Node.js website and follow the installation instructions.\u003c/p\u003e\n\n\u003cp\u003eInstall MongoDB Community Edition from the official MongoDB website and set it up on your local machine or use a cloud-based MongoDB service like MongoDB Atlas.\u003c/p\u003e\n\n\u003cp\u003e\u0026nbsp;\u003c/p\u003e\n\n\u003cdiv style=\"background:#eeeeee;border:1px solid #cccccc;padding:5px 10px;\"\u003e\u003cstrong\u003eStep 2: Initialize Node.js Project\u003c/strong\u003e\u003c/div\u003e\n\n\u003cul\u003e\n\u003c/ul\u003e\n\n\u003cul\u003e\n\u003c/ul\u003e\n\n\u003cp\u003eCreate a new directory for your project. Initialize a new Node.js project using npm (Node Package Manager):\u003c/p\u003e\n\n\u003cpre\u003e\n\u003ccode\u003emkdir my-app\ncd my-app\nnpm init -y\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003e\u0026nbsp;\u003c/p\u003e\n\n\u003cdiv style=\"background:#eeeeee;border:1px solid #cccccc;padding:5px 10px;\"\u003e\u003cstrong\u003eStep 3: Install Dependencies\u003c/strong\u003e\u003c/div\u003e\n\n\u003cul\u003e\n\u003c/ul\u003e\n\n\u003cp\u003eInstall necessary dependencies such as Express.js (for building the API) and Mongoose (for interacting with MongoDB):\u003c/p\u003e\n\n\u003cpre\u003e\n\u003ccode class=\"language-javascript\"\u003enpm install -g express-generator\nnpx express --view=ejs\nnpm install\nnpm install express-flash --save\nnpm install express-session --save\nnpm install body-parser --save\nnpm install cors --save\nnpm install mongoose\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003e\u0026nbsp;\u003c/p\u003e\n\n\u003cp\u003e\u003ca href=\"https://www.npmjs.com/package/body-parser\"\u003e\u003cstrong\u003ebody-parser:\u003c/strong\u003e\u003c/a\u003e\u0026nbsp;Parse incoming request bodies in a middleware before your handlers, available under the\u0026nbsp;\u003ccode\u003ereq.body\u003c/code\u003e\u0026nbsp;property.\u003c/p\u003e\n\n\u003cp\u003e\u003cstrong\u003e\u003ca href=\"https://www.npmjs.com/package/express-flash\" target=\"_blank\"\u003eExpress-Flash\u003c/a\u003e:\u003c/strong\u003e\u0026nbsp;Flash is an extension of\u0026nbsp;\u003ccode\u003econnect-flash\u003c/code\u003e\u0026nbsp;with the ability to define a flash message and render it without redirecting the request.\u003c/p\u003e\n\n\u003cp\u003e\u003cstrong\u003e\u003ca href=\"https://www.npmjs.com/package/express-session\" target=\"_blank\"\u003eExpress-Session\u003c/a\u003e:\u003c/strong\u003e\u0026nbsp;HTTP server-side framework used to create and manage a session middleware.\u003c/p\u003e\n\n\u003cp\u003e\u003cstrong\u003e\u003ca href=\"https://www.npmjs.com/package/express-ejs-layouts\" target=\"_blank\"\u003eExpress-EJS\u003c/a\u003e:\u003c/strong\u003e\u0026nbsp;EJS is\u0026nbsp;a simple templating language\u0026nbsp;that is used to generate HTML markup with plain JavaScript. It also helps to embed JavaScript to HTML pages\u003c/p\u003e\n\n\u003cp\u003e\u003cstrong\u003e\u003ca href=\"https://www.npmjs.com/package/mongoose\" target=\"_blank\"\u003eMongoose\u003c/a\u003e:\u003c/strong\u003e\u0026nbsp;Mongoose is a\u0026nbsp;\u003ca href=\"https://www.mongodb.com/\" target=\"_blank\"\u003eMongoDB\u003c/a\u003e\u0026nbsp;object modeling tool designed to work in an asynchronous environment. Mongoose supports both promises and callbacks.\u003c/p\u003e\n\n\u003cp\u003e\u0026nbsp;\u003c/p\u003e\n\n\u003cdiv style=\"background:#eeeeee;border:1px solid #cccccc;padding:5px 10px;\"\u003e\u003cstrong\u003eStep 4: Connect to MongoDB\u003c/strong\u003e\u003c/div\u003e\n\n\u003cul\u003e\n\u003c/ul\u003e\n\n\u003cp\u003eSet up a connection to your MongoDB database using Mongoose:\u003c/p\u003e\n\n\u003cp\u003e\u003cstrong\u003edatabase.js\u003c/strong\u003e\u003c/p\u003e\n\n\u003cpre\u003e\n\u003ccode class=\"language-javascript\"\u003evar mongoose = require('mongoose');\n\nmongoose.connect('mongodb://localhost:27017/my_database', {useNewUrlParser: true});\n\nvar conn = mongoose.connection;\n\nconn.on('connected', function() {\n    console.log('database is connected successfully');\n});\n\nconn.on('disconnected',function(){\n    console.log('database is disconnected successfully');\n});\n\nconn.on('error', console.error.bind(console, 'connection error:'));\n\nmodule.exports = conn;\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003e\u0026nbsp;\u003c/p\u003e\n\n\u003cdiv style=\"background:#eeeeee;border:1px solid #cccccc;padding:5px 10px;\"\u003e\u003cstrong\u003eStep 5: Define Schema and Model\u003c/strong\u003e\u003c/div\u003e\n\n\u003cp\u003eDefine a schema for your MongoDB documents and create a model using Mongoose. This will define the structure of your data.\u003c/p\u003e\n\n\u003cp\u003e\u003cstrong\u003euserModel.js\u003c/strong\u003e\u003c/p\u003e\n\n\u003cpre\u003e\n\u003ccode class=\"language-javascript\"\u003evar db = require(\"../database\");\nvar mongoose = require('mongoose');\nvar Schema = mongoose.Schema;\n \nvar UserSchema = new Schema({\n    title: String,\n    author: String,\n    category: String\n});\n \nmodule.exports = mongoose.model('User', UserSchema);\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cpre\u003e\n\u0026nbsp;\u003c/pre\u003e\n\n\u003cdiv style=\"background:#eeeeee;border:1px solid #cccccc;padding:5px 10px;\"\u003e\u003cstrong\u003eStep 6: Implement CRUD Operations\u003c/strong\u003e\u003c/div\u003e\n\n\u003cp\u003eImplement controller functions for handling CRUD operations on your MongoDB data.\u003c/p\u003e\n\n\u003cp\u003e\u003cstrong\u003eusers.js\u003c/strong\u003e route file\u003c/p\u003e\n\n\u003cpre\u003e\n\u003ccode class=\"language-javascript\"\u003evar express = require('express');\nvar User = require('../models/user');\nvar router = express.Router();\n \nrouter.get('/', function(req, res){\n    console.log('getting all users');\n    User.find({}).exec(function(err, users){\n        if(err) {\n            res.send('error has occured');\n        } else {\n            console.log(users);\n            res.json(users);\n        }\n    });\n});\n \nrouter.get('/:id', function(req, res){\n    console.log('getting one user');\n    User.findOne({\n        _id: req.params.id\n    }).exec(function(err, user){\n        if(err) {\n            res.send('error has occured');\n        } else {\n            console.log(user);\n            res.json(user);\n        }\n    });\n});\n \nrouter.post('/', function(req, res){\n    var newUser = new User();\n    newUser.title = req.body.title;\n    newUser.author = req.body.author;\n    newUser.category = req.body.category;\n    newUser.save(function(err, user){\n        if(err) {\n            res.send('error saving user');\n        } else {\n            console.log(user);\n            res.send(user);\n        }\n    });\n});\n \nrouter.put('/:id', function(req, res){\n    User.findOneAndUpdate({\n        _id: req.params.id\n    },{\n        $set: {\n            title: req.body.title,\n            author: req.body.author,\n            category: req.body.category\n        }\n    },{\n        upsert: true\n    },function(err, newUser){\n        if(err) {\n            res.send('error updating user');\n        } else {\n            console.log(newUser);\n            res.send(newUser);\n        }\n    });\n});\n \nrouter.delete('/:id', function(req, res){\n    User.findByIdAndRemove({\n        _id: req.params.id\n    },function(err, user){\n        if(err) {\n            res.send('error deleting user');\n        } else {\n            console.log(user);\n            res.send(user);\n        }\n    });\n});\n \nmodule.exports = router;\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cul\u003e\n\u003c/ul\u003e\n\n\u003cp\u003e\u0026nbsp;\u003c/p\u003e\n\n\u003cdiv style=\"background:#eeeeee;border:1px solid #cccccc;padding:5px 10px;\"\u003e\u003cstrong\u003eStep 7: Import Modules in App.js\u003c/strong\u003e\u003c/div\u003e\n\n\u003cp\u003eImport express flash session body-parser Mongoose dependencies in \u003cstrong\u003eapp.js\u003c/strong\u003e\u0026nbsp;as shown below.\u003c/p\u003e\n\n\u003cpre\u003e\n\u003ccode class=\"language-javascript\"\u003econst createError = require('http-errors');\nconst express = require('express');\nconst path = require('path');\nconst cookieParser = require('cookie-parser');\nconst logger = require('morgan');\nconst bodyParser = require('body-parser');\nconst cors = require('cors');\nconst users = require('./routes/users');\nconst app = express();\napp.use(express.json());\napp.use(bodyParser.json());\n \napp.use(bodyParser.urlencoded({\n    extended: true\n}));\n \napp.use(cookieParser());\n \napp.use(cors());\n \napp.use('/users', users);\n \n// Handling Errors\napp.use((err, req, res, next) =\u0026gt; {\n    // console.log(err);\n    err.statusCode = err.statusCode || 500;\n    err.message = err.message || \"Internal Server Error\";\n    res.status(err.statusCode).json({\n        message: err.message,\n    });\n});\n \napp.listen(3000,() =\u0026gt; console.log('Server is running on port 3000'));\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003e\u0026nbsp;\u003c/p\u003e\n\n\u003cdiv style=\"background:#eeeeee;border:1px solid #cccccc;padding:5px 10px;\"\u003e\u003cstrong\u003eStep 8: Run App Server\u003c/strong\u003e\u003c/div\u003e\n\n\u003cp\u003eStart the app server using the following command.\u003c/p\u003e\n\n\u003cpre\u003e\n\u003ccode\u003enpm start\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003e\u0026nbsp;\u003c/p\u003e\n\n\u003chr /\u003e\n\u003cp\u003e\u003cstrong\u003e\u003cbig\u003eYou might also like:\u003c/big\u003e\u003c/strong\u003e\u003c/p\u003e\n\n\u003cul\u003e\n\t\u003cli\u003e\u003cstrong\u003e\u003cbig\u003eRead Also:\u0026nbsp;\u003ca href=\"https://techsolutionstuff.com/post/user-roles-and-permissions-using-centralized-database-in-laravel-10\"\u003eUser Roles and Permissions Using Centralized Database in Laravel 10\u003c/a\u003e\u003c/big\u003e\u003c/strong\u003e\u003c/li\u003e\n\t\u003cli\u003e\u003cstrong\u003e\u003cbig\u003eRead Also:\u0026nbsp;\u003ca href=\"https://techsolutionstuff.com/post/how-to-install-and-setup-mongodb-in-laravel-10\"\u003eHow to Install and Setup MongoDB in Laravel 10\u003c/a\u003e\u003c/big\u003e\u003c/strong\u003e\u003c/li\u003e\n\t\u003cli\u003e\u003cstrong\u003e\u003cbig\u003eRead Also:\u0026nbsp;\u003ca href=\"https://techsolutionstuff.com/post/how-to-insert-data-in-mongodb-using-node-js\"\u003eHow to Insert Data in MongoDB using Node.js\u003c/a\u003e\u003c/big\u003e\u003c/strong\u003e\u003c/li\u003e\n\t\u003cli\u003e\u003cstrong\u003e\u003cbig\u003eRead Also:\u0026nbsp;\u003ca href=\"https://techsolutionstuff.com/post/laravel-10-mongodb-crud-operation\"\u003eLaravel 10 MongoDB CRUD Operation\u003c/a\u003e\u003c/big\u003e\u003c/strong\u003e\u003c/li\u003e\n\u003c/ul\u003e\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftechsolutionstuff%2Fhow-to-create-rest-api-using-node-js-and-mongodb","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftechsolutionstuff%2Fhow-to-create-rest-api-using-node-js-and-mongodb","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftechsolutionstuff%2Fhow-to-create-rest-api-using-node-js-and-mongodb/lists"}