{"info":{"_postman_id":"8f86f5c7-545b-4076-beca-40fbd911782c","name":"MongoDB CRUD API w Node n Express","description":"<html><head></head><body><p><strong>Beginner's Guide to Building a RESTful API with Node.js, Express, and MongoDB</strong><br><strong>Introduction:</strong></p>\n<p>This contains a beginner-friendly guide and implementation of a RESTful API built with Node.js,<br>Express, and MongoDB. The API allows you to manage data, including creating,<br>reading, updating, and deleting records.</p>\n<p><strong>JavaScript:</strong><br>JavaScript is a versatile programming language primarily used for web<br>development. It enables interactive web pages and is essential for building<br>dynamic and responsive web applications.</p>\n<p><strong>Node.js:</strong><br>Node.js is a runtime environment that allows you to run JavaScript code outside<br>of a web browser. It uses an event-driven, non-blocking I/O model, making it<br>lightweight and efficient for building scalable network applications.</p>\n<p><strong>Express.js:</strong><br>Express.js is a minimal and flexible Node.js web application framework that<br>provides a robust set of features for building web and mobile applications. It<br>simplifies the process of creating APIs and handling HTTP requests.</p>\n<p><strong>MongoDB:</strong><br>MongoDB is a NoSQL database that stores data in flexible, JSON-like documents.<br>It is designed for scalability, high availability, and performance, and it<br>facilitates rapid development and iteration of database schemas.</p>\n<p><strong>RESTful API:</strong><br>RESTful API (Representational State Transfer) is an architectural style for<br>designing networked applications. It uses standard HTTP methods (GET, POST,<br>PUT, DELETE) to perform CRUD (Create, Read, Update, Delete) operations on<br>resources. RESTful APIs are widely used for building web services and<br>interacting with data-driven applications.</p>\n<p><strong>Prerequisites</strong></p>\n<p>Basic knowledge of JavaScript, Node.js,<br>and MongoDB</p>\n<p>Installed software: <a href=\"https://nodejs.org/en/download/package-manager\">Node.js</a> , &nbsp;<a href=\"https://www.mongodb.com/try/download/community\">&nbsp;MongoDB</a> , <a href=\"https://www.postman.com/downloads/\">Postman</a> ( click the text for download )<br>IDE: Visual Studio ( as per your choice)</p>\n<p><strong>Setup:</strong></p>\n<p>Setting up the project directory</p>\n<p>Initializing npm and installing<br>dependencies, open Terminal:</p>\n<p>npm init -y</p>\n<p>npm install express cors mongodb</p>\n<p>const express = require('express');<br>const cors = require('cors');<br>const bodyParser = require('body-parser');<br>const { MongoClient, ObjectId } = require('mongodb');</p>\n<p>const app = express();<br>app.use(cors());<br>app.use(bodyParser.json());</p>\n<p>const port = 1100; // Change port if it's already in use<br>//Sample Web- <a href=\"http://localhost:1100/get\">http://localhost:1100/get</a><br>//<a href=\"http://localhost:portnumber/endpoint\">http://localhost:portnumber/</a><br>Database creation in MongoDB</p>\n<p>On the Command Prompt or any terminal add these commands:</p>\n<p>mongod</p>\n<p>mongosh</p>\n<p>For creating new database<br>and collection in MongoDB:</p>\n<p>use playerDB <em>//i named my database name as playerDB you can name it whatever__you want</em></p>\n<p>Now you have to create<br>a collection in this database:</p>\n<p>db.createCollection('playerCollection') <em>// name__it as per your choice</em></p>\n<p>// MongoDB connection<br>const uri = 'mongodb://localhost:27017';<br>const client = new MongoClient(uri);</p>\n<p>// Connect to MongoDB<br>async function connectToMongoDB() {<br>try {<br>await client.connect();<br>console.log('Connected to MongoDB');<br>} catch (err) {<br>console.error('Failed to connect to MongoDB', err);<br>process.exit(1);<br>}<br>}</p>\n<p>connectToMongoDB(); // Must call this function</p>\n<p>const database = client.db('playerDB'); // As per database name<br>const collection = database.collection('playerCollection'); // As per collection name</p>\n<p>app.listen(port, () =&gt;<br>console.log(<code>Server running on ${port}</code>)<br>);</p>\n<p>//Sample MongoDB Data</p>\n<p>// db.playerCollection.insertOne({ name: 'Neymar Jr', position: 'LW', number: 10 })<br>// db.playerCollection.insertOne({ name: 'Lionel Messi', position: 'RW', number: 10 })<br>// db.playerCollection.insertOne({ name: 'Cristiano Ronaldo', position: 'ST', number: 7 })<br>// db.playerCollection.insertOne({ name: 'Sergio Ramos', position: 'CB', number: 4 })<br>// db.playerCollection.insertOne({ name: 'Toni Kross', position: 'CM', number: 8 })</p>\n<p>// MongoDB Command<br>// test&gt; use playerDB<br>// playerDB&gt; db.createCollection('playerCollection')</p>\n<p>Connect with me:</p>\n<p><strong>Abtahi Md. Mahib Uddin</strong></p>\n<p><a href=\"https://github.com/abtaaahi/\">GitHub</a> || <a href=\"https://abtaaahi.github.io/portfolio/\">Portfolio</a> || <a href=\"https://www.linkedin.com/in/abtahi-md-mahib-uddin-6739aa236/\">LinkedIn </a> || <a href=\"https://mailto:abtahimahib@gmail.com\">Email </a> || <a href=\"https://www.facebook.com/abtaaahi/\">Facebook</a></p>\n</body></html>","schema":"https://schema.getpostman.com/json/collection/v2.0.0/collection.json","toc":[],"owner":"36920253","collectionId":"8f86f5c7-545b-4076-beca-40fbd911782c","publishedId":"2sA3kPo46s","public":true,"customColor":{"top-bar":"FFFFFF","right-sidebar":"303030","highlight":"FF6C37"},"publishDate":"2024-07-14T11:02:10.000Z"},"item":[{"name":"http://localhost:1100/get","id":"727be38a-8290-4109-9132-c234801cab61","protocolProfileBehavior":{"disableBodyPruning":true},"request":{"method":"GET","header":[],"url":"http://localhost:1100/get","description":"<p>// Read Data (FETCH)<br />app.get('/get', async (req, res) =&gt; {<br />try {<br />const data = await collection.find({}).toArray();<br />res.send(data);<br />} catch (err) {<br />console.error('Failed to fetch data', err);<br />res.status(500).send({ error: 'Failed to fetch data' });<br />}<br />});</p>\n","urlObject":{"protocol":"http","port":"1100","path":["get"],"host":["localhost"],"query":[],"variable":[]}},"response":[{"id":"eb45154a-b833-4f4d-9446-445bebb52481","name":"output","originalRequest":{"method":"GET","header":[],"url":"http://localhost:1100/get"},"status":"OK","code":200,"_postman_previewlanguage":"json","header":[{"key":"X-Powered-By","value":"Express"},{"key":"Access-Control-Allow-Origin","value":"*"},{"key":"Content-Type","value":"application/json; charset=utf-8"},{"key":"Content-Length","value":"741"},{"key":"ETag","value":"W/\"2e5-qDvjqnTDW7QWNTjZRsIKLP88S/M\""},{"key":"Date","value":"Sat, 13 Jul 2024 18:14:56 GMT"},{"key":"Connection","value":"keep-alive"},{"key":"Keep-Alive","value":"timeout=5"}],"cookie":[],"responseTime":null,"body":"[\n    {\n        \"_id\": \"6692b7eb68d310d1cce8e3e8\",\n        \"name\": \"Neymar Jr\",\n        \"position\": \"LW\",\n        \"number\": 10\n    },\n    {\n        \"_id\": \"6692b80f68d310d1cce8e3e9\",\n        \"name\": \"Lionel Messi\",\n        \"position\": \"RW\",\n        \"number\": 10\n    },\n    {\n        \"_id\": \"6692b82a68d310d1cce8e3ea\",\n        \"name\": \"Cristiano Ronaldo\",\n        \"position\": \"ST\",\n        \"number\": 7\n    },\n    {\n        \"_id\": \"6692b86c68d310d1cce8e3eb\",\n        \"name\": \"Sergio Ramos\",\n        \"position\": \"CB\",\n        \"number\": 4\n    },\n    {\n        \"_id\": \"6692baf968d310d1cce8e3ec\",\n        \"name\": \"Toni Kross\",\n        \"position\": \"CM\",\n        \"number\": 8\n    },\n    {\n        \"_id\": \"6692bd4946544f0cf4cf3779\",\n        \"name\": \"Abtahi\",\n        \"position\": \"LW\",\n        \"number\": 10\n    },\n    {\n        \"_id\": \"6692bd8246544f0cf4cf377a\",\n        \"name\": \"Luka Modric\",\n        \"position\": \"CM\",\n        \"number\": 10\n    },\n    {\n        \"_id\": \"6692be22c38a127b7c967097\",\n        \"name\": \"Mahib\",\n        \"position\": \"LW\",\n        \"number\": 10\n    },\n    {\n        \"_id\": \"6692bebfcad0ff9c6902546f\",\n        \"name\": \"Silva\",\n        \"position\": \"CB\",\n        \"number\": 3\n    }\n]"}],"_postman_id":"727be38a-8290-4109-9132-c234801cab61"},{"name":"http://localhost:1100/post","id":"12d3fe3c-d115-4754-9ff0-859e99b15957","protocolProfileBehavior":{"disableBodyPruning":true},"request":{"method":"POST","header":[],"body":{"mode":"raw","raw":"{\r\n    \"name\": \"Marcelo\",\r\n    \"position\": \"RB\",\r\n    \"number\": 4\r\n}","options":{"raw":{"language":"json"}}},"url":"http://localhost:1100/post","description":"<p>// Create Data (ADD)<br />app.post('/post', async (req, res) =&gt; {<br />try {<br />const newItem = req.body;<br />const result = await collection.insertOne(newItem);<br />res.status(201).send({ insertedId: result.insertedId });<br />} catch (err) {<br />console.error('Failed to add item', err);<br />res.status(500).send({ error: <code>Failed to create item: ${err.message}</code> });<br />}<br />});</p>\n","urlObject":{"protocol":"http","port":"1100","path":["post"],"host":["localhost"],"query":[],"variable":[]}},"response":[{"id":"b7af770e-869f-4baa-9016-c636e185dbea","name":"output","originalRequest":{"method":"POST","header":[],"body":{"mode":"raw","raw":"{\r\n    \"name\": \"Marcelo\",\r\n    \"position\": \"RB\",\r\n    \"number\": 4\r\n}","options":{"raw":{"language":"json"}}},"url":"http://localhost:1100/post"},"status":"Created","code":201,"_postman_previewlanguage":"json","header":[{"key":"X-Powered-By","value":"Express"},{"key":"Access-Control-Allow-Origin","value":"*"},{"key":"Content-Type","value":"application/json; charset=utf-8"},{"key":"Content-Length","value":"41"},{"key":"ETag","value":"W/\"29-bgjiNUz3ArSTo/kMszd6oX8FjnA\""},{"key":"Date","value":"Sat, 13 Jul 2024 18:15:23 GMT"},{"key":"Connection","value":"keep-alive"},{"key":"Keep-Alive","value":"timeout=5"}],"cookie":[],"responseTime":null,"body":"{\n    \"insertedId\": \"6692c43b3915f0de3beb3209\"\n}"}],"_postman_id":"12d3fe3c-d115-4754-9ff0-859e99b15957"},{"name":"http://localhost:1110/delete/6692be05c38a127b7c967096","id":"dd0a3cdb-4fb8-48e4-982a-1c8a87db76c4","protocolProfileBehavior":{"disableBodyPruning":true},"request":{"method":"DELETE","header":[],"url":"http://localhost:1100/delete/6692be22c38a127b7c967097","description":"<p>// Delete Data (DELETE)<br />app.delete('/delete/:id', async (req, res) =&gt; {<br />try {<br />const id = req.params.id;<br />console.log(<code>Deleting player with id: ${id}</code>); // Log the id being deleted<br />const result = await collection.deleteOne({ _id: new ObjectId(id) });<br />if (result.deletedCount === 0) {<br />return res.status(404).send({ error: 'Player not found' });<br />}<br />res.send({ message: 'Player deleted' });<br />} catch (err) {<br />console.error('Failed to delete player', err);<br />res.status(500).send({ error: <code>Failed to delete player: ${err.message}</code> });<br />}<br />});</p>\n","urlObject":{"protocol":"http","port":"1100","path":["delete","6692be22c38a127b7c967097"],"host":["localhost"],"query":[],"variable":[]}},"response":[{"id":"53dd7234-bc79-478f-8c04-e08c18813deb","name":"output","originalRequest":{"method":"DELETE","header":[],"url":"http://localhost:1100/delete/6692be22c38a127b7c967097"},"status":"OK","code":200,"_postman_previewlanguage":"json","header":[{"key":"X-Powered-By","value":"Express"},{"key":"Access-Control-Allow-Origin","value":"*"},{"key":"Content-Type","value":"application/json; charset=utf-8"},{"key":"Content-Length","value":"28"},{"key":"ETag","value":"W/\"1c-UKr0b9qJAubQh6W0U7A3uoMVpks\""},{"key":"Date","value":"Sat, 13 Jul 2024 18:15:53 GMT"},{"key":"Connection","value":"keep-alive"},{"key":"Keep-Alive","value":"timeout=5"}],"cookie":[],"responseTime":null,"body":"{\n    \"message\": \"Player deleted\"\n}"}],"_postman_id":"dd0a3cdb-4fb8-48e4-982a-1c8a87db76c4"},{"name":"http://localhost:1100/update/6692bd8246544f0cf4cf377a","id":"003a0a33-f852-4cbf-9bff-ab3495630dfc","protocolProfileBehavior":{"disableBodyPruning":true},"request":{"method":"PUT","header":[],"body":{"mode":"raw","raw":"{\r\n    \"name\": \"Luka Modric\",\r\n    \"position\": \"CM\",\r\n    \"number\": 10\r\n}\r\n","options":{"raw":{"language":"json"}}},"url":"http://localhost:1100/update/6692bd8246544f0cf4cf377a","description":"<p>// Update Data (UPDATE)<br />app.put('/update/:id', async (req, res) =&gt; {<br />try {<br />const id = req.params.id;<br />if (!ObjectId.isValid(id)) {<br />return res.status(400).send({ error: 'Invalid ID format' });<br />}<br />const updatedItem = req.body;<br />const result = await collection.updateOne(<br />{ _id: new ObjectId(id) },<br />{ $set: updatedItem }<br />);<br />if (result.matchedCount === 0) {<br />return res.status(404).send({ error: 'Player not found' });<br />}<br />res.send({ message: 'Player updated' });<br />} catch (err) {<br />console.error('Failed to update player', err);<br />res.status(500).send({ error: <code>Failed to update player: ${err.message}</code> });<br />}<br />});</p>\n","urlObject":{"protocol":"http","port":"1100","path":["update","6692bd8246544f0cf4cf377a"],"host":["localhost"],"query":[],"variable":[]}},"response":[{"id":"0966b0a8-25b4-44ff-bacf-69c973bf8392","name":"output","originalRequest":{"method":"PUT","header":[],"body":{"mode":"raw","raw":"{\r\n    \"name\": \"Luka Modric\",\r\n    \"position\": \"CM\",\r\n    \"number\": 10\r\n}\r\n","options":{"raw":{"language":"json"}}},"url":"http://localhost:1100/update/6692bd8246544f0cf4cf377a"},"status":"OK","code":200,"_postman_previewlanguage":"json","header":[{"key":"X-Powered-By","value":"Express"},{"key":"Access-Control-Allow-Origin","value":"*"},{"key":"Content-Type","value":"application/json; charset=utf-8"},{"key":"Content-Length","value":"28"},{"key":"ETag","value":"W/\"1c-TV8+rAze3dFG6L9CmXmWcbyoz48\""},{"key":"Date","value":"Sat, 13 Jul 2024 18:16:28 GMT"},{"key":"Connection","value":"keep-alive"},{"key":"Keep-Alive","value":"timeout=5"}],"cookie":[],"responseTime":null,"body":"{\n    \"message\": \"Player updated\"\n}"}],"_postman_id":"003a0a33-f852-4cbf-9bff-ab3495630dfc"}]}