{"id":28733,"date":"2024-04-06T01:23:52","date_gmt":"2024-04-06T00:23:52","guid":{"rendered":"https:\/\/nelkodev.com\/blog\/guia-completa-para-desarrollar-una-api-rest-con-node-js-y-mongodb\/"},"modified":"2024-06-03T18:43:52","modified_gmt":"2024-06-03T17:43:52","slug":"guia-completa-para-desarrollar-una-api-rest-con-node-js-y-mongodb","status":"publish","type":"post","link":"https:\/\/nelkodev.com\/en\/blog\/complete-guide-to-developing-a-rest-api-with-node-js-and-mongodb\/","title":{"rendered":"Complete Guide to Develop a REST API with Node.js and MongoDB"},"content":{"rendered":"<p>Developing REST APIs using Node.js along with MongoDB has become one of the most popular and powerful combinations in the world of web development. This approach not only makes it easier to build scalable and efficient applications, but also promotes good practices in handling large volumes of data and concurrent connections. In this walkthrough, we&#039;ll explore how you can build your own REST API using these technologies, ensuring you implement best practices for optimal, maintainable performance.<\/p>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_80 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #ffffff;color:#ffffff\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewbox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #ffffff;color:#ffffff\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewbox=\"0 0 24 24\" version=\"1.2\" baseprofile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/nelkodev.com\/en\/blog\/complete-guide-to-developing-a-rest-api-with-node-js-and-mongodb\/#Comenzando_con_el_Entorno_de_Desarrollo\" >Getting started with the Development Environment<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/nelkodev.com\/en\/blog\/complete-guide-to-developing-a-rest-api-with-node-js-and-mongodb\/#Inicializando_tu_Proyecto_Nodejs\" >Initializing your Node.js Project<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/nelkodev.com\/en\/blog\/complete-guide-to-developing-a-rest-api-with-node-js-and-mongodb\/#Estructurando_la_API\" >Structuring the API<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/nelkodev.com\/en\/blog\/complete-guide-to-developing-a-rest-api-with-node-js-and-mongodb\/#Configurando_el_Servidor\" >Configuring the Server<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/nelkodev.com\/en\/blog\/complete-guide-to-developing-a-rest-api-with-node-js-and-mongodb\/#Modelos_con_Mongoose\" >Models with Mongoose<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/nelkodev.com\/en\/blog\/complete-guide-to-developing-a-rest-api-with-node-js-and-mongodb\/#Creando_Rutas_y_Controladores\" >Creating Routes and Controllers<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/nelkodev.com\/en\/blog\/complete-guide-to-developing-a-rest-api-with-node-js-and-mongodb\/#Pruebas_y_Buenas_Practicas\" >Testing and Good Practices<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/nelkodev.com\/en\/blog\/complete-guide-to-developing-a-rest-api-with-node-js-and-mongodb\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"Comenzando_con_el_Entorno_de_Desarrollo\"><\/span>Getting started with the Development Environment<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Before we dive into the code, it&#039;s crucial to properly configure our development environment. You will need the following:<\/p>\n<ul>\n<li><strong>Node.js<\/strong>: The JavaScript execution environment on the server.<\/li>\n<li><strong>MongoDB<\/strong>: The NoSQL database that we will use to store data.<\/li>\n<li><strong>A code editor<\/strong>: Like Visual Studio Code, which is widely used and offers great support for JavaScript.<\/li>\n<\/ul>\n<p>Once you have Node.js and MongoDB installed, create a new folder for your project and open this folder in your code editor. <\/p>\n<p>To verify that Node.js is correctly installed, you can run the following command in your terminal:<\/p>\n<pre><code class=\"&quot;language-bash&quot;\">node --version<\/code><\/pre>\n<p>You should see the Node.js version printed to the console. Likewise, make sure MongoDB is running correctly on your system.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Inicializando_tu_Proyecto_Nodejs\"><\/span>Initializing your Node.js Project<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Inside your project folder, you will run the following command to start a new Node.js project:<\/p>\n<pre><code class=\"&quot;language-bash&quot;\">npm init -y<\/code><\/pre>\n<p>This command creates a file <code>package.json<\/code> that manages the dependencies of your project. Next, install the essential dependencies for our API server:<\/p>\n<pre><code class=\"&quot;language-bash&quot;\">npm install express mongoose body-parser dotenv<\/code><\/pre>\n<ul>\n<li><strong>Express<\/strong>: A framework for web applications that makes it easy to create HTTP servers.<\/li>\n<li><strong>Mongoose<\/strong>: An object modeling library for MongoDB and Node.js that makes it easy to interact with the database.<\/li>\n<li><strong>Body-parser<\/strong>: Middleware that parses the incoming body of HTTP requests before your handlers receive them.<\/li>\n<li><strong>Dotenv<\/strong>: A module that loads environment variables from a file <code>.env<\/code>.<\/li>\n<\/ul>\n<h2><span class=\"ez-toc-section\" id=\"Estructurando_la_API\"><\/span>Structuring the API<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The structure of your project is crucial to keeping it organized and scalable. Here is a suggested directory structure:<\/p>\n<pre><code>\/api-project |-- \/node_modules |-- \/models |-- \/routes |-- \/controllers |-- app.js |-- .env |-- package.json<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Configurando_el_Servidor\"><\/span>Configuring the Server<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>In the File <code>app.js<\/code>, we will configure our Express server and connect to MongoDB through Mongoose:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">const express = require(&#039;express&#039;); const mongoose = require(&#039;mongoose&#039;); require(&#039;dotenv&#039;).config(); const app = express(); app.use(express.json()); mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() =&gt; console.log(&#039;MongoDB Connected&#039;)) .catch(err =&gt; console.log(err) ); const port = process.env.PORT || 3000; app.listen(port, () =&gt; { console.log(`Server running on port ${port}`); });<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Modelos_con_Mongoose\"><\/span>Models with Mongoose<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Inside the folder <code>\/models<\/code>, you can define the schemas of your data. For example, for a user model:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">const mongoose = require(&#039;mongoose&#039;); const { Schema } = mongoose; const userSchema = new Schema({ username: { type: String, required: true, unique: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true } }); const User = mongoose.model(&#039;User&#039;, userSchema); module.exports = User;<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Creando_Rutas_y_Controladores\"><\/span>Creating Routes and Controllers<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Organize your API routes in the folder <code>\/routes<\/code> and the drivers in <code>\/controllers<\/code>. For example:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">\/\/ \/routes\/userRoutes.js const express = require(&#039;express&#039;); const router = express.Router(); const userController = require(&#039;..\/controllers\/userController&#039;); router.post(&#039;\/register&#039;, userController.registerUser); router.post(&#039;\/login&#039;, userController.loginUser); module.exports = router;<\/code><\/pre>\n<p>And the corresponding driver:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">\/\/ \/controllers\/userController.js const User = require(&#039;..\/models\/User&#039;); exports.registerUser = async (req, res) =&gt; { try { const { username, email, password } = req.body; const user = new User({ username, email, password }); await user.save(); res.status(201).send(&#039;User registered&#039;); } catch (error) { res.status(500).json({ error: error.message }); } }; exports.loginUser = async (req, res) =&gt; { \/\/ Implement login logic };<\/code><\/pre>\n<h2><span class=\"ez-toc-section\" id=\"Pruebas_y_Buenas_Practicas\"><\/span>Testing and Good Practices<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>It is essential to test your API to ensure that everything works as expected. You can use Postman or any other API client to make requests to your server and check the responses.<\/p>\n<p>Regarding good practices:<\/p>\n<ul>\n<li>Use clear and concise variable names.<\/li>\n<li>Handles errors appropriately and provides helpful responses.<\/li>\n<li>Keep your code clean and well commented.<\/li>\n<\/ul>\n<h2><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Developing a REST API with Node.js and MongoDB may seem overwhelming at first, but by following these steps and structuring your project efficiently, you can do it in a much more accessible and maintainable way. Don&#039;t hesitate to visit <a href=\"https:\/\/nelkodev.com\/en\/contact\/\">the contact page<\/a> if you have any questions or need additional advice.<\/p>","protected":false},"excerpt":{"rendered":"<p>Developing REST APIs using Node.js together with MongoDB has become one of the most popular and powerful combinations in the world of web development. This approach not only makes it easier to build scalable and efficient applications, but also promotes good practices in handling large volumes of data and [\u2026]<\/p>","protected":false},"author":1,"featured_media":28734,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[420,2207,1913],"tags":[667,1344,205,500,90,1708,358,1912,1193,2208,60,1008,1325,37],"class_list":["post-28733","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog","category-nodejs","category-pruebas-de-backend","tag-api","tag-backend","tag-blog","tag-completa","tag-con","tag-desarrollar","tag-guia","tag-mongodb","tag-node-js","tag-nodejs","tag-para","tag-pruebas","tag-rest","tag-una"],"_links":{"self":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/28733","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/comments?post=28733"}],"version-history":[{"count":0,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/28733\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media\/28734"}],"wp:attachment":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media?parent=28733"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/categories?post=28733"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/tags?post=28733"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}