|
1 |
| -# how-to-create-rest-api-using-node-js-and-mongodb |
2 |
| -Welcome to my article on creating a RESTful API using Node.js and MongoDB. |
| 1 | +# How to Create REST API using Node.js and MongoDB |
| 2 | + |
| 3 | +<p>Hey there! Welcome to my article on creating a RESTful API using Node.js and MongoDB. If you're looking to build powerful and scalable web applications, understanding how to create a robust API is essential.</p> |
| 4 | + |
| 5 | +<p>In this guide, I'll walk you through the process of building a REST API step by step using express.js and mongoDB.</p> |
| 6 | + |
| 7 | +<p>A 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.</p> |
| 8 | + |
| 9 | +<p>These HTTP methods provide a standardized way for clients to interact with the server and perform CRUD (Create, Read, Update, Delete) operations on resources.</p> |
| 10 | + |
| 11 | +<p>So, let'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.</p> |
| 12 | + |
| 13 | +<div style="background:#eeeeee;border:1px solid #cccccc;padding:5px 10px;"><strong>Step 1: Setup Development Environment</strong></div> |
| 14 | + |
| 15 | +<p>Ensure Node.js is installed on your machine. You can download it from the official Node.js website and follow the installation instructions.</p> |
| 16 | + |
| 17 | +<p>Install 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.</p> |
| 18 | + |
| 19 | +<p> </p> |
| 20 | + |
| 21 | +<div style="background:#eeeeee;border:1px solid #cccccc;padding:5px 10px;"><strong>Step 2: Initialize Node.js Project</strong></div> |
| 22 | + |
| 23 | +<ul> |
| 24 | +</ul> |
| 25 | + |
| 26 | +<ul> |
| 27 | +</ul> |
| 28 | + |
| 29 | +<p>Create a new directory for your project. Initialize a new Node.js project using npm (Node Package Manager):</p> |
| 30 | + |
| 31 | +<pre> |
| 32 | +<code>mkdir my-app |
| 33 | +cd my-app |
| 34 | +npm init -y</code></pre> |
| 35 | + |
| 36 | +<p> </p> |
| 37 | + |
| 38 | +<div style="background:#eeeeee;border:1px solid #cccccc;padding:5px 10px;"><strong>Step 3: Install Dependencies</strong></div> |
| 39 | + |
| 40 | +<ul> |
| 41 | +</ul> |
| 42 | + |
| 43 | +<p>Install necessary dependencies such as Express.js (for building the API) and Mongoose (for interacting with MongoDB):</p> |
| 44 | + |
| 45 | +<pre> |
| 46 | +<code class="language-javascript">npm install -g express-generator |
| 47 | +npx express --view=ejs |
| 48 | +npm install |
| 49 | +npm install express-flash --save |
| 50 | +npm install express-session --save |
| 51 | +npm install body-parser --save |
| 52 | +npm install cors --save |
| 53 | +npm install mongoose |
| 54 | +</code></pre> |
| 55 | + |
| 56 | +<p> </p> |
| 57 | + |
| 58 | +<p><a href="https://www.npmjs.com/package/body-parser"><strong>body-parser:</strong></a> Parse incoming request bodies in a middleware before your handlers, available under the <code>req.body</code> property.</p> |
| 59 | + |
| 60 | +<p><strong><a href="https://www.npmjs.com/package/express-flash" target="_blank">Express-Flash</a>:</strong> Flash is an extension of <code>connect-flash</code> with the ability to define a flash message and render it without redirecting the request.</p> |
| 61 | + |
| 62 | +<p><strong><a href="https://www.npmjs.com/package/express-session" target="_blank">Express-Session</a>:</strong> HTTP server-side framework used to create and manage a session middleware.</p> |
| 63 | + |
| 64 | +<p><strong><a href="https://www.npmjs.com/package/express-ejs-layouts" target="_blank">Express-EJS</a>:</strong> EJS is a simple templating language that is used to generate HTML markup with plain JavaScript. It also helps to embed JavaScript to HTML pages</p> |
| 65 | + |
| 66 | +<p><strong><a href="https://www.npmjs.com/package/mongoose" target="_blank">Mongoose</a>:</strong> Mongoose is a <a href="https://www.mongodb.com/" target="_blank">MongoDB</a> object modeling tool designed to work in an asynchronous environment. Mongoose supports both promises and callbacks.</p> |
| 67 | + |
| 68 | +<p> </p> |
| 69 | + |
| 70 | +<div style="background:#eeeeee;border:1px solid #cccccc;padding:5px 10px;"><strong>Step 4: Connect to MongoDB</strong></div> |
| 71 | + |
| 72 | +<ul> |
| 73 | +</ul> |
| 74 | + |
| 75 | +<p>Set up a connection to your MongoDB database using Mongoose:</p> |
| 76 | + |
| 77 | +<p><strong>database.js</strong></p> |
| 78 | + |
| 79 | +<pre> |
| 80 | +<code class="language-javascript">var mongoose = require('mongoose'); |
| 81 | + |
| 82 | +mongoose.connect('mongodb://localhost:27017/my_database', {useNewUrlParser: true}); |
| 83 | + |
| 84 | +var conn = mongoose.connection; |
| 85 | + |
| 86 | +conn.on('connected', function() { |
| 87 | + console.log('database is connected successfully'); |
| 88 | +}); |
| 89 | + |
| 90 | +conn.on('disconnected',function(){ |
| 91 | + console.log('database is disconnected successfully'); |
| 92 | +}); |
| 93 | + |
| 94 | +conn.on('error', console.error.bind(console, 'connection error:')); |
| 95 | + |
| 96 | +module.exports = conn;</code></pre> |
| 97 | + |
| 98 | +<p> </p> |
| 99 | + |
| 100 | +<div style="background:#eeeeee;border:1px solid #cccccc;padding:5px 10px;"><strong>Step 5: Define Schema and Model</strong></div> |
| 101 | + |
| 102 | +<p>Define a schema for your MongoDB documents and create a model using Mongoose. This will define the structure of your data.</p> |
| 103 | + |
| 104 | +<p><strong>userModel.js</strong></p> |
| 105 | + |
| 106 | +<pre> |
| 107 | +<code class="language-javascript">var db = require("../database"); |
| 108 | +var mongoose = require('mongoose'); |
| 109 | +var Schema = mongoose.Schema; |
| 110 | + |
| 111 | +var UserSchema = new Schema({ |
| 112 | + title: String, |
| 113 | + author: String, |
| 114 | + category: String |
| 115 | +}); |
| 116 | + |
| 117 | +module.exports = mongoose.model('User', UserSchema); |
| 118 | +</code></pre> |
| 119 | + |
| 120 | +<pre> |
| 121 | + </pre> |
| 122 | + |
| 123 | +<div style="background:#eeeeee;border:1px solid #cccccc;padding:5px 10px;"><strong>Step 6: Implement CRUD Operations</strong></div> |
| 124 | + |
| 125 | +<p>Implement controller functions for handling CRUD operations on your MongoDB data.</p> |
| 126 | + |
| 127 | +<p><strong>users.js</strong> route file</p> |
| 128 | + |
| 129 | +<pre> |
| 130 | +<code class="language-javascript">var express = require('express'); |
| 131 | +var User = require('../models/user'); |
| 132 | +var router = express.Router(); |
| 133 | + |
| 134 | +router.get('/', function(req, res){ |
| 135 | + console.log('getting all users'); |
| 136 | + User.find({}).exec(function(err, users){ |
| 137 | + if(err) { |
| 138 | + res.send('error has occured'); |
| 139 | + } else { |
| 140 | + console.log(users); |
| 141 | + res.json(users); |
| 142 | + } |
| 143 | + }); |
| 144 | +}); |
| 145 | + |
| 146 | +router.get('/:id', function(req, res){ |
| 147 | + console.log('getting one user'); |
| 148 | + User.findOne({ |
| 149 | + _id: req.params.id |
| 150 | + }).exec(function(err, user){ |
| 151 | + if(err) { |
| 152 | + res.send('error has occured'); |
| 153 | + } else { |
| 154 | + console.log(user); |
| 155 | + res.json(user); |
| 156 | + } |
| 157 | + }); |
| 158 | +}); |
| 159 | + |
| 160 | +router.post('/', function(req, res){ |
| 161 | + var newUser = new User(); |
| 162 | + newUser.title = req.body.title; |
| 163 | + newUser.author = req.body.author; |
| 164 | + newUser.category = req.body.category; |
| 165 | + newUser.save(function(err, user){ |
| 166 | + if(err) { |
| 167 | + res.send('error saving user'); |
| 168 | + } else { |
| 169 | + console.log(user); |
| 170 | + res.send(user); |
| 171 | + } |
| 172 | + }); |
| 173 | +}); |
| 174 | + |
| 175 | +router.put('/:id', function(req, res){ |
| 176 | + User.findOneAndUpdate({ |
| 177 | + _id: req.params.id |
| 178 | + },{ |
| 179 | + $set: { |
| 180 | + title: req.body.title, |
| 181 | + author: req.body.author, |
| 182 | + category: req.body.category |
| 183 | + } |
| 184 | + },{ |
| 185 | + upsert: true |
| 186 | + },function(err, newUser){ |
| 187 | + if(err) { |
| 188 | + res.send('error updating user'); |
| 189 | + } else { |
| 190 | + console.log(newUser); |
| 191 | + res.send(newUser); |
| 192 | + } |
| 193 | + }); |
| 194 | +}); |
| 195 | + |
| 196 | +router.delete('/:id', function(req, res){ |
| 197 | + User.findByIdAndRemove({ |
| 198 | + _id: req.params.id |
| 199 | + },function(err, user){ |
| 200 | + if(err) { |
| 201 | + res.send('error deleting user'); |
| 202 | + } else { |
| 203 | + console.log(user); |
| 204 | + res.send(user); |
| 205 | + } |
| 206 | + }); |
| 207 | +}); |
| 208 | + |
| 209 | +module.exports = router; |
| 210 | +</code></pre> |
| 211 | + |
| 212 | +<ul> |
| 213 | +</ul> |
| 214 | + |
| 215 | +<p> </p> |
| 216 | + |
| 217 | +<div style="background:#eeeeee;border:1px solid #cccccc;padding:5px 10px;"><strong>Step 7: Import Modules in App.js</strong></div> |
| 218 | + |
| 219 | +<p>Import express flash session body-parser Mongoose dependencies in <strong>app.js</strong> as shown below.</p> |
| 220 | + |
| 221 | +<pre> |
| 222 | +<code class="language-javascript">const createError = require('http-errors'); |
| 223 | +const express = require('express'); |
| 224 | +const path = require('path'); |
| 225 | +const cookieParser = require('cookie-parser'); |
| 226 | +const logger = require('morgan'); |
| 227 | +const bodyParser = require('body-parser'); |
| 228 | +const cors = require('cors'); |
| 229 | +const users = require('./routes/users'); |
| 230 | +const app = express(); |
| 231 | +app.use(express.json()); |
| 232 | +app.use(bodyParser.json()); |
| 233 | + |
| 234 | +app.use(bodyParser.urlencoded({ |
| 235 | + extended: true |
| 236 | +})); |
| 237 | + |
| 238 | +app.use(cookieParser()); |
| 239 | + |
| 240 | +app.use(cors()); |
| 241 | + |
| 242 | +app.use('/users', users); |
| 243 | + |
| 244 | +// Handling Errors |
| 245 | +app.use((err, req, res, next) => { |
| 246 | + // console.log(err); |
| 247 | + err.statusCode = err.statusCode || 500; |
| 248 | + err.message = err.message || "Internal Server Error"; |
| 249 | + res.status(err.statusCode).json({ |
| 250 | + message: err.message, |
| 251 | + }); |
| 252 | +}); |
| 253 | + |
| 254 | +app.listen(3000,() => console.log('Server is running on port 3000')); |
| 255 | +</code></pre> |
| 256 | + |
| 257 | +<p> </p> |
| 258 | + |
| 259 | +<div style="background:#eeeeee;border:1px solid #cccccc;padding:5px 10px;"><strong>Step 8: Run App Server</strong></div> |
| 260 | + |
| 261 | +<p>Start the app server using the following command.</p> |
| 262 | + |
| 263 | +<pre> |
| 264 | +<code>npm start</code></pre> |
| 265 | + |
| 266 | +<p> </p> |
| 267 | + |
| 268 | +<hr /> |
| 269 | +<p><strong><big>You might also like:</big></strong></p> |
| 270 | + |
| 271 | +<ul> |
| 272 | + <li><strong><big>Read Also: <a href="https://techsolutionstuff.com/post/user-roles-and-permissions-using-centralized-database-in-laravel-10">User Roles and Permissions Using Centralized Database in Laravel 10</a></big></strong></li> |
| 273 | + <li><strong><big>Read Also: <a href="https://techsolutionstuff.com/post/how-to-install-and-setup-mongodb-in-laravel-10">How to Install and Setup MongoDB in Laravel 10</a></big></strong></li> |
| 274 | + <li><strong><big>Read Also: <a href="https://techsolutionstuff.com/post/how-to-insert-data-in-mongodb-using-node-js">How to Insert Data in MongoDB using Node.js</a></big></strong></li> |
| 275 | + <li><strong><big>Read Also: <a href="https://techsolutionstuff.com/post/laravel-10-mongodb-crud-operation">Laravel 10 MongoDB CRUD Operation</a></big></strong></li> |
| 276 | +</ul> |
0 commit comments