{"id":10140,"date":"2024-04-21T12:32:30","date_gmt":"2024-04-21T07:02:30","guid":{"rendered":"https:\/\/codeforgeek.com\/?p=10140"},"modified":"2024-04-22T13:01:59","modified_gmt":"2024-04-22T07:31:59","slug":"mongodb-findbyid-function","status":"publish","type":"post","link":"https:\/\/codeforgeek.com\/mongodb-findbyid-function\/","title":{"rendered":"Mongoose findById() Function: Selecting MongoDB Document by ID"},"content":{"rendered":"\n<p>As a MERN fan, we all have a favourite database, MongoDB. While working with it we usually use the <a href=\"https:\/\/codeforgeek.com\/nodejs-mongodb-select\/\">find()<\/a> method to select or query multiple documents, on the other hand, we use <a href=\"https:\/\/codeforgeek.com\/findone-function-in-mongodb\/\">findOne()<\/a> to get one.\u00a0<\/p>\n\n\n\n<p>We can also use this findOne() with an ID passed as a query to select that specific ID-contained document. But there is a better and more straightforward way to do so, introducing <strong>findById() <\/strong>from Mongoose.<\/p>\n\n\n\n<p>Well, why Mongoose? Why not MongoDB? MongoDB has no such function that lets us quickly select a document based on the document ID. This function is not a native MongoDB function but is only provided by Mongoose.<\/p>\n\n\n\n<p>In this tutorial, we will not only look at its basics but also demonstrate it with a complete example.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Mongoose findById() Function<\/strong><\/h2>\n\n\n\n<p>Mongoose is an ODM (Object Document Mapper). It is also called an object modelling tool. It is built on top of the MongoDB driver making it easier to interact with the MongoDB database, especially while using Node.js. The functions provided by Mongoose are beginner-friendly, easy to use, and require fewer lines of code than MongoDB native functions. One such function is findById() to match a document based on ID, let&#8217;s see its syntax.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Syntax of findById() Function<\/strong><\/h3>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\ncollection.findById(id, callback);\n<\/pre><\/div>\n\n\n<p><strong>Parameters:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>collection:<\/strong> A Mongoose model that represents a MongoDB collection,<\/li>\n\n\n\n<li><strong>id:<\/strong> The ID of a document you want to get,<\/li>\n\n\n\n<li><strong>callback:<\/strong> A callback function that is executed when a document is found or an error occurs.<\/li>\n<\/ul>\n\n\n\n<p><strong>Note:<\/strong><\/p>\n\n\n\n<p>It also takes some optional parameters, which isn&#8217;t that big of a use case. Check out the<a href=\"https:\/\/mongoosejs.com\/docs\/api.html#model_Model.findById\" target=\"_blank\" rel=\"noopener\"> official docs<\/a> if you want to learn about them.<\/p>\n\n\n\n<p><strong>Return:<\/strong><\/p>\n\n\n\n<p>The function itself returns not a document but a Mongoose Query object that you can use inside the callback to perform further operations or print it. If documents are not found, the callback will receive null.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Complete Guide to Using findById() with Node.js and MongoDB<\/strong><\/h2>\n\n\n\n<p>Well now that we have learned all the basics, syntax and parameters, let&#8217;s see how to implement it in Node.js to filter documents.<\/p>\n\n\n\n<p><strong>Below is a step-by-step guide to using the findById() in a Node.js application with the help of Mongoose ODM:<\/strong><\/p>\n\n\n\n<p><strong>Step 1: <\/strong>Create a Node.js project directory and move into it.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nmkdir newNodeProject\ncd newNodeProject\n<\/pre><\/div>\n\n\n<p><strong>Step 2: <\/strong>Initialise<strong> <\/strong>the<strong> <\/strong>Node.js project inside the directory using npm.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nnpm init -y\n<\/pre><\/div>\n\n\n<p>This command will now create a &#8220;package.json&#8221; file in the directory, here you will be able to change the entry point file name by changing the \u201cmain\u201d key. However, let&#8217;s now stick to the default.<\/p>\n\n\n\n<p><strong>Step 3:<\/strong> Create the entry point JavaScript file.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\ntouch index.js\n<\/pre><\/div>\n\n\n<p><strong>Step 4:<\/strong> Next, install all the required packages for this application.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nnpm i express mongoose\n<\/pre><\/div>\n\n\n<p><strong>Step 5: <\/strong>Import all the packages we installed. We will use the require() method to achieve this. You can simply copy the code below in the index.js file.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nconst express = require(&#039;express&#039;);\nconst app = express();\nconst mongoose = require(&#039;mongoose&#039;);\n<\/pre><\/div>\n\n\n<p><strong>Step 6:<\/strong> Next, connect the application to the MongoDB local database server using Mongoose.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nmongoose.connect(&#039;mongodb:\/\/localhost:27017\/someRandomDB&#039;, { useNewUrlParser: true, useUnifiedTopology: true })\n    .then(() =&gt; {\n        console.log(`CONNECTED TO MONGO!`);\n    })\n    .catch((err) =&gt; {\n        console.log(`OH NO! MONGO CONNECTION ERROR!`);\n        console.log(err);\n    })\n<\/pre><\/div>\n\n\n<p><strong>Step 7:<\/strong> Now at the very end of the index.js file, specify the port for the app to listen on.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\napp.listen(3000, () =&gt; {\n    console.log(&#039;Connected to PORT 3000...&#039;);\n})\n<\/pre><\/div>\n\n\n<p><strong>Step 8: <\/strong>In your project directory, create a folder named &#8220;models&#8221;.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nmkdir models\n<\/pre><\/div>\n\n\n<p>We usually do this when to conform to the MVC (Models, Views, &amp; Controllers) format when using Express. However, you can simply choose to add the contents of the file in the index.js file. But for standards, we will choose to create a model directory.<\/p>\n\n\n\n<p><strong>Step 9:<\/strong> If you choose to create a &#8220;models&#8221; directory, create a new file inside that directory named first_model.js or anything you like.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\ntouch models\/first_model.js\n<\/pre><\/div>\n\n\n<p><strong>Step 10: <\/strong>Import Mongoose and create a schema and model in this file. Let\u2019s say we are managing a mini-shoe store database. This is what our products\u2019 schema would look like.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nconst mongoose = require(&#039;mongoose&#039;);\nconst shoeSchema = new mongoose.Schema({\n    name: {\n        type: String,\n        required: true\n    },\n    price: {\n        type: Number,\n        required: true,\n        min: 0\n    },\n    sizeUK: {\n        type: Number,\n        required: true,\n        min: 5\n    },\n    onSale: {\n        type: Boolean,\n        default: false\n    }\n})\n \nconst Shoe = mongoose.model(&#039;Shoe&#039;, productSchema);\n<\/pre><\/div>\n\n\n<p><strong>Step 11:<\/strong> To work with the findbyId(), we have created and saved a few documents in the &#8220;shoes&#8221; collection.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\n{ &quot;_id&quot; : 1000, &quot;name&quot; : &quot;Nike Air Force 1&quot;, &quot;price&quot; : 4,999, &quot;sizeUK&quot; : 6, &quot;onSale&quot; : false }\n{ &quot;_id&quot; : 1001, &quot;name&quot; : &quot;X Speedflow.4 Flexible Ground Boots&quot;, &quot;price&quot; : 5,999, &quot;sizeUK&quot; : 7, &quot;onSale&quot; : true }\n{ &quot;_id&quot; : 1002, &quot;name&quot; : &quot;Men&#039;s Reebok Running Ztaur Run Shoes&quot;, &quot;price&quot; : 9,999, &quot;sizeUK&quot; : 9, &quot;onSale&quot; : true }\n{ &quot;_id&quot; : 1003, &quot;name&quot; : &quot;Puma RS - Z Art of Sport Unisex Sneakers&quot;, &quot;price&quot; : 8,999, &quot;sizeUK&quot; : 8, &quot;onSale&quot; : true }\n<\/pre><\/div>\n\n\n<p><strong>Step 12: <\/strong>Let us now use the findbyId() on these documents to find a document containing a specific ID field.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nconst id = 1002;\n\nShoe.findById(id, function (err, shoe) {\n    if (err) throw error;\n    console.log(`Item(s) found: ${shoe.name}`);\n});\n<\/pre><\/div>\n\n\n<p>Inside the callback, check for an error and throw it if it is present, if not then print the selected document in the console.<\/p>\n\n\n\n<p><strong>Step 13: <\/strong>Finally, you can run the app to see if it works.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nnode models\/first_model.js\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nItem(s) found: Men&#039;s Reebok Running Ztaur Run Shoes\n<\/pre><\/div>\n\n\n<p>This way we have successfully used the findById() function to find a document by its ID.<\/p>\n\n\n\n<p><strong>Read More:<\/strong><a href=\"https:\/\/codeforgeek.com\/list-collections-databases-users-mongodb\/\"><strong> Listing All Collections, Databases, and Users in the MongoDB Shell<\/strong><\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>This is the end of this tutorial and if you are still here appreciate yourself, very few people make it this far. We hope you have got enough information on find by ID. We also gave you some knowledge of how to set up a basic Node application, connect to the MongoDB database, use Mongoose, etc. The purpose of building this big application is not just to explain to you how to use the findById(), but also to give you its complete case use.\u00a0<\/p>\n","protected":false},"excerpt":{"rendered":"<p>As a MERN fan, we all have a favourite database, MongoDB. While working with it we usually use the find() method to select or query multiple documents, on the other hand, we use findOne() to get one.\u00a0 We can also use this findOne() with an ID passed as a query to select that specific ID-contained [&hellip;]<\/p>\n","protected":false},"author":70,"featured_media":29688,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_surecart_dashboard_logo_width":"180px","_surecart_dashboard_show_logo":true,"_surecart_dashboard_navigation_orders":true,"_surecart_dashboard_navigation_invoices":true,"_surecart_dashboard_navigation_subscriptions":true,"_surecart_dashboard_navigation_downloads":true,"_surecart_dashboard_navigation_billing":true,"_surecart_dashboard_navigation_account":true,"_uag_custom_page_level_css":"","footnotes":""},"categories":[11],"tags":[],"class_list":["post-10140","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-mongodb"],"blocksy_meta":[],"uagb_featured_image_src":{"full":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/Mongoose-findById-Function.png",1280,720,false],"thumbnail":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/Mongoose-findById-Function-150x150.png",150,150,true],"medium":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/Mongoose-findById-Function-300x169.png",300,169,true],"medium_large":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/Mongoose-findById-Function-768x432.png",768,432,true],"large":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/Mongoose-findById-Function-1024x576.png",1024,576,true],"1536x1536":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/Mongoose-findById-Function.png",1280,720,false],"2048x2048":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/Mongoose-findById-Function.png",1280,720,false]},"uagb_author_info":{"display_name":"Aneesha S","author_link":"https:\/\/codeforgeek.com\/author\/aneesha\/"},"uagb_comment_info":0,"uagb_excerpt":"As a MERN fan, we all have a favourite database, MongoDB. While working with it we usually use the find() method to select or query multiple documents, on the other hand, we use findOne() to get one.\u00a0 We can also use this findOne() with an ID passed as a query to select that specific ID-contained&hellip;","_links":{"self":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/10140","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/users\/70"}],"replies":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/comments?post=10140"}],"version-history":[{"count":0,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/10140\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/media\/29688"}],"wp:attachment":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/media?parent=10140"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/categories?post=10140"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/tags?post=10140"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}