<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sarani Peiris on Medium]]></title>
        <description><![CDATA[Stories by Sarani Peiris on Medium]]></description>
        <link>https://medium.com/@saranipeiris17?source=rss-c804abf0832b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*dpPpDNfmsfDTn01O</url>
            <title>Stories by Sarani Peiris on Medium</title>
            <link>https://medium.com/@saranipeiris17?source=rss-c804abf0832b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:37:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saranipeiris17/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Efficient Photo Storage in MongoDB: GridFS vs. Metadata Storage]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@saranipeiris17/efficient-photo-storage-in-mongodb-gridfs-vs-metadata-storage-e48c61ca6044?source=rss-c804abf0832b------2"><img src="https://cdn-images-1.medium.com/max/797/0*boBeaNwIK6R1C0mh" width="797"></a></p><p class="medium-feed-snippet">Storing photos in MongoDB using Mongoose typically involves handling images as binary data or storing file metadata and paths. Here are&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@saranipeiris17/efficient-photo-storage-in-mongodb-gridfs-vs-metadata-storage-e48c61ca6044?source=rss-c804abf0832b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@saranipeiris17/efficient-photo-storage-in-mongodb-gridfs-vs-metadata-storage-e48c61ca6044?source=rss-c804abf0832b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e48c61ca6044</guid>
            <dc:creator><![CDATA[Sarani Peiris]]></dc:creator>
            <pubDate>Mon, 26 Aug 2024 02:54:50 GMT</pubDate>
            <atom:updated>2024-08-26T02:54:50.437Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Understanding Mongoose: Simplifying MongoDB Integration in Node.js Applications]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@saranipeiris17/understanding-mongoose-simplifying-mongodb-integration-in-node-js-applications-632f75a0b509?source=rss-c804abf0832b------2"><img src="https://cdn-images-1.medium.com/max/800/0*vvYFDe9KPoLJDsX4" width="800"></a></p><p class="medium-feed-snippet">Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a higher-level abstraction over the native MongoDB&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@saranipeiris17/understanding-mongoose-simplifying-mongodb-integration-in-node-js-applications-632f75a0b509?source=rss-c804abf0832b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@saranipeiris17/understanding-mongoose-simplifying-mongodb-integration-in-node-js-applications-632f75a0b509?source=rss-c804abf0832b------2</link>
            <guid isPermaLink="false">https://medium.com/p/632f75a0b509</guid>
            <dc:creator><![CDATA[Sarani Peiris]]></dc:creator>
            <pubDate>Mon, 26 Aug 2024 02:54:39 GMT</pubDate>
            <atom:updated>2024-08-26T02:54:39.345Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[MongoDB vs. Mongoose: Understanding the Key Differences and Benefits]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@saranipeiris17/mongodb-vs-mongoose-understanding-the-key-differences-and-benefits-405f0d388326?source=rss-c804abf0832b------2"><img src="https://cdn-images-1.medium.com/max/1080/0*VhytkXQ6-rk5YeOC.png" width="1080"></a></p><p class="medium-feed-snippet">MongoDB and Mongoose are often used together in Node.js applications, but they serve different purposes. Here&#x2019;s a clear comparison of the&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@saranipeiris17/mongodb-vs-mongoose-understanding-the-key-differences-and-benefits-405f0d388326?source=rss-c804abf0832b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@saranipeiris17/mongodb-vs-mongoose-understanding-the-key-differences-and-benefits-405f0d388326?source=rss-c804abf0832b------2</link>
            <guid isPermaLink="false">https://medium.com/p/405f0d388326</guid>
            <dc:creator><![CDATA[Sarani Peiris]]></dc:creator>
            <pubDate>Mon, 26 Aug 2024 02:54:10 GMT</pubDate>
            <atom:updated>2024-08-26T02:54:10.587Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[An Introduction to DevOps: Bridging Development and Operations for Faster, Reliable Software…]]></title>
            <link>https://medium.com/@saranipeiris17/an-introduction-to-devops-bridging-development-and-operations-for-faster-reliable-software-c94046c624e5?source=rss-c804abf0832b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c94046c624e5</guid>
            <dc:creator><![CDATA[Sarani Peiris]]></dc:creator>
            <pubDate>Sun, 25 Aug 2024 14:37:59 GMT</pubDate>
            <atom:updated>2024-08-25T14:37:59.178Z</atom:updated>
            <content:encoded><![CDATA[<h3>An Introduction to DevOps: Bridging Development and Operations for Faster, Reliable Software Delivery</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/0*UsspF7Z2Xg2uf6mz.png" /></figure><h3>What is DevOps?</h3><p>DevOps is a comprehensive approach that combines software development (Dev) and IT operations (Ops) to accelerate the delivery of high-quality software. The primary goal of DevOps is to shorten the development life cycle while delivering features, fixes, and updates frequently in close alignment with business objectives. It fosters a culture of collaboration between teams that historically worked in silos, namely development and operations, and emphasizes automation, continuous integration, continuous delivery (CI/CD), and continuous monitoring.</p><h3>Core Principles of DevOps</h3><ol><li><strong>Collaboration and Integration</strong>:</li></ol><ul><li>DevOps encourages closer collaboration between developers, who write the code, and operations teams, who manage the deployment and maintenance of the applications. This collaboration ensures that both teams share responsibility for the software from development through to production.</li></ul><p><strong>2. Automation</strong>:</p><ul><li>Automation is key in DevOps, reducing manual effort and human error. It involves automating repetitive tasks such as code testing, deployment, and environment provisioning.</li></ul><p><strong>3. Continuous Integration/Continuous Delivery (CI/CD)</strong>:</p><ul><li><strong>Continuous Integration (CI)</strong>: Developers frequently merge their code changes into a central repository where automated builds and tests run. This helps to catch and fix issues early in the development process.</li><li><strong>Continuous Delivery (CD)</strong>: Builds on CI by automating the release of validated code to a production environment, ensuring that it is always in a deployable state.</li></ul><p><strong>4. Infrastructure as Code (IaC)</strong>:</p><ul><li>IaC involves managing and provisioning infrastructure through code, rather than manual processes. This allows for consistent and repeatable infrastructure deployments, often using tools like Terraform or Ansible.</li></ul><p><strong>5. Monitoring and Feedback Loops</strong>:</p><ul><li>Continuous monitoring of applications and infrastructure ensures that any issues in production can be detected and resolved quickly. Feedback loops from monitoring data are essential for continuous improvement.</li></ul><h3>A Basic Example of DevOps in Action</h3><p>Imagine a small e-commerce company that wants to implement DevOps to improve the speed and reliability of its software releases. Here’s how DevOps would be applied:</p><ol><li><strong>Development</strong>:</li></ol><ul><li>Developers work on new features for the e-commerce platform. They write code and commit changes to a shared Git repository. With DevOps, they ensure that their code is modular and follows best practices.</li></ul><p><strong>2. Continuous Integration (CI)</strong>:</p><ul><li>Every time a developer pushes code to the repository, an automated CI pipeline is triggered. This pipeline runs a series of automated tests to verify that the code works as expected and doesn’t introduce new bugs. Tools like Jenkins or GitLab CI could be used for this purpose.</li></ul><p><strong>3. Continuous Delivery (CD)</strong>:</p><ul><li>Once the code passes all the automated tests, the CD pipeline automatically prepares it for deployment. The code is packaged and deployed to a staging environment that mirrors the production environment. If everything works well in staging, the code is ready for production deployment.</li></ul><p><strong>4. Infrastructure as Code (IaC)</strong>:</p><ul><li>The infrastructure needed to run the e-commerce platform (servers, databases, load balancers) is defined in code using tools like Terraform. This code is versioned and can be automatically applied to set up the required infrastructure in any environment (e.g., staging, production).</li></ul><p><strong>5. Deployment</strong>:</p><ul><li>The operations team (or a fully automated process) deploys the new version of the application to the production environment. Because everything is automated, deployment can be frequent and reliable, with minimal downtime.</li></ul><p><strong>5. Monitoring</strong>:</p><ul><li>Once the application is live, monitoring tools (like Prometheus or Datadog) keep track of its performance and detect any anomalies or issues in real time. Alerts can be configured to notify the team if something goes wrong, allowing for quick responses.</li></ul><p><strong>6. Feedback Loop</strong>:</p><ul><li>Feedback from monitoring, user reports, and performance metrics is fed back to the development team. This continuous feedback loop helps in making iterative improvements to the application.</li></ul><h3>Example Scenario: Deploying a New Feature</h3><p>Let’s say the e-commerce company wants to introduce a new feature — a discount coupon system.</p><ul><li><strong>Development</strong>: Developers write the code for the discount coupon system and test it locally. They then commit their code to the shared repository.</li><li><strong>CI/CD Pipeline</strong>: Upon committing, the CI/CD pipeline automatically runs tests. If the tests pass, the pipeline proceeds to package the feature and deploy it to a staging environment.</li><li><strong>Staging Environment</strong>: In staging, the team reviews the feature, conducts further testing, and ensures that the feature integrates well with the existing system.</li><li><strong>Production Deployment</strong>: Once approved, the feature is automatically deployed to the production environment with minimal manual intervention. The IaC ensures that any required infrastructure changes (e.g., new database tables for the coupons) are applied consistently.</li><li><strong>Monitoring and Feedback</strong>: After deployment, monitoring tools track the feature’s performance and usage. If any issues are detected (e.g., a sudden spike in error rates), alerts are sent to the team, and they can quickly roll back the change or push a fix.</li></ul><h3>Benefits of This Approach:</h3><ul><li><strong>Faster Deployment</strong>: New features can be deployed quickly and reliably, often multiple times a day.</li><li><strong>Reduced Errors</strong>: Automated testing and deployment reduce the chances of human error, leading to more stable releases.</li><li><strong>Scalability</strong>: The infrastructure can be easily scaled up or down as needed, thanks to IaC.</li><li><strong>Continuous Improvement</strong>: The feedback loop ensures that the application is constantly being improved based on real-time data.</li></ul><p>In summary, DevOps enables companies to deliver software more quickly and reliably by fostering collaboration between teams, automating processes, and continuously integrating and deploying code. The approach also emphasizes continuous monitoring and feedback to ensure that the software meets users’ needs and performs well in production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c94046c624e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprehensive MongoDB Guide: Explore Essential Topics and Techniques]]></title>
            <link>https://medium.com/@saranipeiris17/comprehensive-mongodb-guide-explore-essential-topics-and-techniques-7fb2b6e0397b?source=rss-c804abf0832b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fb2b6e0397b</guid>
            <dc:creator><![CDATA[Sarani Peiris]]></dc:creator>
            <pubDate>Fri, 23 Aug 2024 11:17:17 GMT</pubDate>
            <atom:updated>2024-08-23T11:17:17.850Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*bRaNwZ8wQfzKGLel.png" /></figure><p>MongoDB is a powerful, flexible NoSQL database that is widely used for modern web applications. This blog covers a broad range of topics and techniques to help you master MongoDB, from installation to advanced querying and optimization. Here’s an overview of the key topics covered:</p><h4>1. Introduction to MongoDB</h4><ul><li><a href="https://medium.com/@saranipeiris17/f1bf37211a2d"><strong>What is MongoDB?</strong></a></li></ul><p>Overview of MongoDB’s architecture and benefits.</p><h4>2. Setting Up MongoDB</h4><ul><li><a href="https://medium.com/@saranipeiris17/78a993e53060"><strong>Installing MongoDB</strong></a></li></ul><p>Step-by-step installation guide for MongoDB.</p><ul><li><a href="https://medium.com/@saranipeiris17/creating-a-local-mongodb-database-56102329b97f"><strong>Creating a Local MongoDB Database</strong></a></li></ul><p>Instructions for setting up a local MongoDB database.</p><h4>3. Understanding MongoDB Tools</h4><ul><li><a href="https://medium.com/@saranipeiris17/mongodb-compass-e1d8462ec9f7"><strong>MongoDB Compass</strong></a></li></ul><p>Introduction to MongoDB Compass, the GUI for MongoDB.</p><ul><li><a href="https://medium.com/@saranipeiris17/e4754034944d"><strong>Mastering MongoDB Compass: A Comprehensive Guide to Creating Databases, Collections, and Managing Data</strong></a></li></ul><p>In-depth guide on using MongoDB Compass for database and data management.</p><ul><li><a href="https://medium.com/@saranipeiris17/mongodb-compass-vs-mongo-shell-understanding-the-differences-7301f96bb776"><strong>MongoDB Compass vs. Mongo Shell: Understanding the Differences</strong></a></li></ul><p>Comparison of MongoDB Compass and Mongo Shell, their use cases, and differences.</p><ul><li><a href="https://medium.com/@saranipeiris17/getting-started-with-mongodb-shell-installation-basic-commands-and-advanced-operations-16d4ede43e11"><strong>Getting Started with MongoDB Shell: Installation, Basic Commands, and Advanced Operations</strong></a></li></ul><p>A detailed guide on installing MongoDB Shell, learning essential commands, and performing advanced operations.</p><h4>4. Working with MongoDB Data</h4><ul><li><a href="https://medium.com/@saranipeiris17/mongodb-collections-documents-62ebf2c7d202"><strong>MongoDB — Collections &amp; Documents</strong></a></li></ul><p>Understanding how MongoDB organizes data into collections and documents.</p><ul><li><a href="https://medium.com/@saranipeiris17/filter-documents-with-a-query-09c475681572"><strong>Filter Documents with a Query</strong></a></li></ul><p>Techniques for filtering documents using queries.</p><ul><li><a href="#querying-arrays-in-mongodb"><strong>Querying Arrays in MongoDB: A Comprehensive Guide</strong></a></li></ul><p>Advanced querying techniques for working with arrays.</p><ul><li><a href="#optimizing-mongodb-queries-with-in-and-nin"><strong>Optimizing MongoDB Queries with $in and $nin</strong></a></li></ul><p>Optimization strategies using $in and $nin operators.</p><ul><li><a href="https://medium.com/@saranipeiris17/deleting-documents-in-mongodb-a-comprehensive-guide-b6e34f3603e1"><strong>Deleting Documents in MongoDB: A Comprehensive Guide</strong></a></li></ul><p>Methods and best practices for deleting documents.</p><ul><li><a href="https://medium.com/@saranipeiris17/9f8d0a89aa90"><strong>Updating Documents in MongoDB: Best Practices and Techniques</strong></a></li></ul><p>Techniques for updating documents and maintaining data consistency.</p><h4>5. Using MongoDB Drivers</h4><ul><li><a href="https://medium.com/@saranipeiris17/understanding-mongodb-drivers-c44b2727495f"><strong>Understanding MongoDB Drivers</strong></a></li></ul><p>Overview of MongoDB drivers for various programming languages.</p><ul><li><a href="https://medium.com/@saranipeiris17/step-by-step-guide-to-using-the-mongodb-node-js-driver-ddceaf1faafd"><strong>Step-by-Step Guide to Using the MongoDB Node.js Driver</strong></a></li></ul><p>Guide to using the MongoDB Node.js driver for database operations.</p><ul><li><a href="https://medium.com/@saranipeiris17/bc60c03e40bf"><strong>Step-by-Step Guide to Using MongoDB Node.js Driver with Express.js</strong></a></li></ul><p>Integration of MongoDB Node.js driver with Express.js for building RESTful APIs.</p><ul><li><a href="https://medium.com/@saranipeiris17/c3ab261c8d05"><strong>Connecting Your Node.js Application to MongoDB: A Step-by-Step Guide</strong></a></li></ul><p>Detailed instructions for connecting Node.js applications to MongoDB.</p><h4>6. Advanced Data Handling</h4><ul><li><a href="https://medium.com/@saranipeiris17/caf3de5d946e"><strong>Efficient Data Retrieval with Cursors &amp; Fetching in MongoDB</strong></a></li></ul><p>Techniques for efficient data retrieval using cursors.</p><ul><li><a href="https://medium.com/@saranipeiris17/5c0048461161"><strong>Finding Single Documents in MongoDB</strong></a></li></ul><p>Methods for retrieving single documents from MongoDB.</p><ul><li><a href="https://medium.com/@saranipeiris17/347fce32d94d"><strong>Using Postman to Find Single Documents in MongoDB</strong></a></li></ul><p>How to use Postman for querying MongoDB and finding documents.</p><ul><li><a href="https://medium.com/@saranipeiris17/handling-post-delete-and-patch-requests-in-mongodb-with-node-js-and-express-a40eb38f6de8"><strong>Handling POST, DELETE, and PATCH Requests in MongoDB with Node.js and Express</strong></a></li></ul><p>Handling various HTTP requests with MongoDB in Node.js and Express applications.</p><ul><li><a href="https://medium.com/@saranipeiris17/8b94125117a7"><strong>Implementing Pagination in MongoDB with Node.js and Express</strong></a></li></ul><p>Techniques for implementing pagination in MongoDB.</p><ul><li><a href="https://medium.com/@saranipeiris17/3875c640a96b"><strong>Understanding and Implementing Indexes in MongoDB</strong></a></li></ul><p>How to use and manage indexes in MongoDB for performance optimization.</p><h4>7. MongoDB Atlas</h4><ul><li><a href="https://medium.com/@saranipeiris17/mongodb-atlas-c41da0eb0b51"><strong>MongoDB Atlas</strong></a></li></ul><p>MongoDB Atlas is a fully managed cloud database service that allows you to deploy, manage, and scale MongoDB clusters across multiple cloud providers with ease. It offers robust features such as automated backups, performance monitoring, and global replication, making it an ideal solution for modern, high-performance applications.</p><ul><li><a href="https://medium.com/@saranipeiris17/getting-started-with-mongodb-atlas-a-comprehensive-guide-ef53614d919c"><strong>Getting Started with MongoDB Atlas: A Comprehensive Guide</strong></a></li></ul><p>Guide to setting up and managing MongoDB clusters on Atlas.</p><p>This comprehensive guide covers everything you need to know about MongoDB, from installation to advanced querying and optimization. Each section is designed to provide you with the knowledge and tools to effectively work with MongoDB and build robust, scalable applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fb2b6e0397b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with MongoDB Atlas: A Comprehensive Guide]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">MongoDB Atlas is a fully managed cloud database service provided by MongoDB. It offers a range of features for deploying, managing, and&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@saranipeiris17/getting-started-with-mongodb-atlas-a-comprehensive-guide-ef53614d919c?source=rss-c804abf0832b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@saranipeiris17/getting-started-with-mongodb-atlas-a-comprehensive-guide-ef53614d919c?source=rss-c804abf0832b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef53614d919c</guid>
            <dc:creator><![CDATA[Sarani Peiris]]></dc:creator>
            <pubDate>Fri, 23 Aug 2024 11:13:20 GMT</pubDate>
            <atom:updated>2024-08-23T11:13:20.774Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Understanding and Implementing Indexes in MongoDB]]></title>
            <link>https://medium.com/@saranipeiris17/understanding-and-implementing-indexes-in-mongodb-3875c640a96b?source=rss-c804abf0832b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3875c640a96b</guid>
            <dc:creator><![CDATA[Sarani Peiris]]></dc:creator>
            <pubDate>Fri, 23 Aug 2024 11:12:55 GMT</pubDate>
            <atom:updated>2024-08-23T11:12:55.308Z</atom:updated>
            <content:encoded><![CDATA[<p>Indexes are critical for optimizing query performance in MongoDB. They allow for faster data retrieval by reducing the amount of data scanned during queries. This guide covers the basics of MongoDB indexes, their types, and how to create and use them with Node.js and Express.</p><h4>1. What is an Index?</h4><p>An index in MongoDB is a data structure that improves the speed of data retrieval operations on a collection. Without indexes, MongoDB must perform a full collection scan, which can be slow for large datasets. Indexes are similar to the index in a book, which helps you quickly locate the information you need.</p><h4>2. Types of Indexes</h4><p>MongoDB supports various types of indexes, including:</p><ul><li><strong>Single Field Index</strong>: Indexes on a single field. The most common type.</li><li><strong>Compound Index</strong>: Indexes on multiple fields. Useful for queries that filter on multiple fields.</li><li><strong>Multikey Index</strong>: Indexes on arrays. Helps query documents where the indexed field is an array.</li><li><strong>Geospatial Index</strong>: Indexes for location-based queries.</li><li><strong>Text Index</strong>: Indexes for full-text search.</li><li><strong>Hashed Index</strong>: Indexes for sharding and hashing values.</li></ul><h4>3. Creating Indexes</h4><p><strong>Step 1: Create an Index Using MongoDB Shell</strong></p><p>You can create indexes using the MongoDB shell with the createIndex method:</p><pre>db.collection.createIndex({ fieldName: 1 }) // 1 for ascending, -1 for descending</pre><p>For example, to create an ascending index on the email field:</p><pre>db.users.createIndex({ email: 1 });</pre><p><strong>Step 2: Create an Index Using Node.js</strong></p><p>You can also create indexes programmatically using the MongoDB Node.js driver. Here’s how you can create an index in your server.js file:</p><pre>const express = require(&#39;express&#39;);<br>const { MongoClient } = require(&#39;mongodb&#39;);<br><br>const app = express();<br>const port = 3000;<br><br>const uri = &#39;mongodb://localhost:27017&#39;;<br>const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });<br><br>app.use(express.json());<br><br>// Connect to MongoDB<br>client.connect().then(async () =&gt; {<br>  console.log(&#39;Connected to MongoDB&#39;);<br>  <br>  const database = client.db(&#39;testdb&#39;);<br>  const collection = database.collection(&#39;users&#39;);<br>  <br>  // Create an index on the email field<br>  await collection.createIndex({ email: 1 });<br>}).catch((err) =&gt; {<br>  console.error(&#39;Failed to connect to MongoDB&#39;, err);<br>});<br><br>app.listen(port, () =&gt; {<br>  console.log(`Server running on http://localhost:${port}`);<br>});</pre><h4>4. Viewing Indexes</h4><p>To view existing indexes on a collection:</p><ul><li><strong>MongoDB Shell</strong>:</li></ul><p>db.collection.getIndexes();</p><ul><li><strong>Node.js</strong>:</li><li>You can list indexes using the listIndexes method:</li></ul><p>const indexes = await collection.listIndexes().toArray(); console.log(indexes);</p><h4>5. Index Management</h4><p>Indexes can impact performance, so managing them is crucial:</p><ul><li><strong>Drop an Index</strong>: To remove an index, use dropIndex in the MongoDB shell or dropIndexes method in Node.js:</li></ul><p>db.collection.dropIndex(&#39;indexName&#39;);</p><p>await collection.dropIndex(&#39;indexName&#39;);</p><ul><li><strong>Rebuild Indexes</strong>: Rebuild an index if it becomes fragmented:</li></ul><p>db.collection.reIndex();</p><p>await collection.reIndex();</p><h4>6. Testing Indexes with Postman</h4><p>Indexes generally don’t have a direct testing mechanism in Postman. However, you can test the performance improvement:</p><ol><li>Perform a query with and without an index.</li><li>Measure the response time to ensure the index improves query performance.</li></ol><p>For example:</p><p><strong>Without Index</strong>:</p><ul><li>Set up a query that scans a large dataset.</li><li>Measure response time using Postman.</li></ul><p><strong>With Index</strong>:</p><ul><li>Create an index on the field used in the query.</li><li>Re-run the query and measure response time again.</li></ul><h4>7. Conclusion</h4><p>Indexes are vital for optimizing query performance in MongoDB. By understanding different types of indexes and how to create, manage, and view them, you can significantly improve the efficiency of data retrieval operations. Implementing and testing indexes ensures that your application remains responsive and scalable, even as your dataset grows.</p><p>Feel free to experiment with different types of indexes and monitor their impact on query performance to best suit your application’s needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3875c640a96b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Pagination in MongoDB with Node.js and Express]]></title>
            <link>https://medium.com/@saranipeiris17/implementing-pagination-in-mongodb-with-node-js-and-express-8b94125117a7?source=rss-c804abf0832b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b94125117a7</guid>
            <dc:creator><![CDATA[Sarani Peiris]]></dc:creator>
            <pubDate>Fri, 23 Aug 2024 11:12:23 GMT</pubDate>
            <atom:updated>2024-08-23T11:12:23.785Z</atom:updated>
            <content:encoded><![CDATA[<p>Pagination is essential for managing large datasets by breaking them into manageable chunks. This guide explains how to implement pagination in MongoDB using Node.js and Express, and how to test it with Postman.</p><h4>1. Setting Up Your Node.js and Express Application</h4><p>Assuming you already have a basic setup with Node.js, Express, and MongoDB, follow these steps to add pagination functionality:</p><p><strong>Step 1: Install Required Packages</strong></p><p>If you haven’t already, ensure you have Express and the MongoDB driver installed:</p><pre>npm install express mongodb</pre><p><strong>Step 2: Create the Server</strong></p><p>Update your server.js file to include pagination functionality. Here’s how you can modify it to support paginated results:</p><pre>const express = require(&#39;express&#39;);<br>const { MongoClient, ObjectId } = require(&#39;mongodb&#39;);<br><br>const app = express();<br>const port = 3000;<br><br>const uri = &#39;mongodb://localhost:27017&#39;;<br>const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });<br><br>app.use(express.json());<br><br>// Connect to MongoDB<br>client.connect().then(() =&gt; {<br>  console.log(&#39;Connected to MongoDB&#39;);<br>}).catch((err) =&gt; {<br>  console.error(&#39;Failed to connect to MongoDB&#39;, err);<br>});<br><br>const database = client.db(&#39;testdb&#39;);<br>const collection = database.collection(&#39;testcollection&#39;);<br><br>// GET: Paginated documents<br>app.get(&#39;/documents&#39;, async (req, res) =&gt; {<br>  const page = parseInt(req.query.page) || 1;<br>  const limit = parseInt(req.query.limit) || 10;<br><br>  try {<br>    const documents = await collection.find()<br>      .skip((page - 1) * limit) // Skip documents for previous pages<br>      .limit(limit) // Limit the number of documents<br>      .toArray();<br>      <br>    const totalDocuments = await collection.countDocuments();<br>    <br>    res.json({<br>      page,<br>      limit,<br>      totalDocuments,<br>      totalPages: Math.ceil(totalDocuments / limit),<br>      documents<br>    });<br>  } catch (err) {<br>    res.status(500).send(&#39;Error fetching documents&#39;);<br>  }<br>});<br><br>app.listen(port, () =&gt; {<br>  console.log(`Server running on http://localhost:${port}`);<br>});</pre><p>In this example, the endpoint /documents accepts two query parameters: page and limit. The page parameter specifies which page of results to fetch, and the limit parameter specifies how many documents per page.</p><h4>2. Testing Pagination with Postman</h4><p><strong>Step 1: Open Postman</strong></p><p>Open Postman on your computer.</p><p><strong>Step 2: Create a New Request</strong></p><ol><li>Click on the <strong>New</strong> button or the <strong>+</strong> tab to open a new request.</li><li>Set the request method to GET.</li><li>Enter the URL of your endpoint with query parameters for pagination. For example:</li></ol><ul><li><a href="http://localhost:3000/documents?page=1&amp;limit=5">http://localhost:3000/documents?page=1&amp;limit=5</a></li></ul><p>4. Click <strong>Send</strong>.</p><p><strong>Step 3: Review the Response</strong></p><p>The response will include the paginated documents and metadata about the pagination:</p><pre>{<br>  &quot;page&quot;: 1,<br>  &quot;limit&quot;: 5,<br>  &quot;totalDocuments&quot;: 50,<br>  &quot;totalPages&quot;: 10,<br>  &quot;documents&quot;: [<br>    { &quot;_id&quot;: &quot;60d21b4667d0d8992e610c85&quot;, &quot;name&quot;: &quot;John Doe&quot;, &quot;email&quot;: &quot;john.doe@example.com&quot; },<br>    { &quot;_id&quot;: &quot;60d21b4667d0d8992e610c86&quot;, &quot;name&quot;: &quot;Jane Smith&quot;, &quot;email&quot;: &quot;jane.smith@example.com&quot; },<br>    // more documents...<br>  ]<br>}</pre><ul><li>page: The current page number.</li><li>limit: The number of documents per page.</li><li>totalDocuments: The total number of documents in the collection.</li><li>totalPages: The total number of pages based on the limit.</li><li>documents: An array of documents for the current page.</li></ul><h4>3. Conclusion</h4><p>Pagination is a crucial feature for efficiently handling large datasets in MongoDB. By implementing pagination in your Node.js and Express application, you can provide a more manageable and user-friendly way to navigate through data. Testing pagination with Postman ensures that your pagination logic works correctly and handles data retrieval as expected.</p><p>Feel free to extend this setup with additional features such as sorting, filtering, or searching to enhance the usability of your API.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b94125117a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling POST, DELETE, and PATCH Requests in MongoDB with Node.js and Express]]></title>
            <link>https://medium.com/@saranipeiris17/handling-post-delete-and-patch-requests-in-mongodb-with-node-js-and-express-a40eb38f6de8?source=rss-c804abf0832b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a40eb38f6de8</guid>
            <dc:creator><![CDATA[Sarani Peiris]]></dc:creator>
            <pubDate>Fri, 23 Aug 2024 11:11:49 GMT</pubDate>
            <atom:updated>2024-08-23T11:11:49.695Z</atom:updated>
            <content:encoded><![CDATA[<p>In this guide, we’ll expand on our Node.js and Express setup to handle POST, DELETE, and PATCH requests for MongoDB. These operations are crucial for creating, updating, and deleting documents in a MongoDB collection.</p><h4>1. Setting Up Your Node.js and Express Application</h4><p>Ensure you have a basic setup with Node.js, Express, and MongoDB. If you haven’t done so already, follow these steps:</p><p><strong>Step 1: Initialize the Project</strong></p><pre>mkdir mongodb-postman-demo<br>cd mongodb-postman-demo<br>npm init -y</pre><p><strong>Step 2: Install Required Packages</strong></p><pre>npm install express mongodb</pre><p><strong>Step 3: Create the Server</strong></p><p>Create a file named server.js and include the following code:</p><pre>const express = require(&#39;express&#39;);<br>const { MongoClient, ObjectId } = require(&#39;mongodb&#39;);<br><br>const app = express();<br>const port = 3000;<br><br>const uri = &#39;mongodb://localhost:27017&#39;;<br>const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });<br><br>app.use(express.json());<br><br>// Connect to MongoDB<br>client.connect().then(() =&gt; {<br>  console.log(&#39;Connected to MongoDB&#39;);<br>}).catch((err) =&gt; {<br>  console.error(&#39;Failed to connect to MongoDB&#39;, err);<br>});<br><br>const database = client.db(&#39;testdb&#39;);<br>const collection = database.collection(&#39;testcollection&#39;);<br><br>// POST: Create a new document<br>app.post(&#39;/documents&#39;, async (req, res) =&gt; {<br>  try {<br>    const newDocument = req.body;<br>    const result = await collection.insertOne(newDocument);<br>    res.status(201).json({ _id: result.insertedId, ...newDocument });<br>  } catch (err) {<br>    res.status(500).send(&#39;Error creating document&#39;);<br>  }<br>});<br><br>// DELETE: Remove a document by ID<br>app.delete(&#39;/documents/:id&#39;, async (req, res) =&gt; {<br>  const id = req.params.id;<br>  try {<br>    const result = await collection.deleteOne({ _id: ObjectId(id) });<br>    if (result.deletedCount === 1) {<br>      res.status(200).send(&#39;Document deleted&#39;);<br>    } else {<br>      res.status(404).send(&#39;Document not found&#39;);<br>    }<br>  } catch (err) {<br>    res.status(500).send(&#39;Error deleting document&#39;);<br>  }<br>});<br><br>// PATCH: Update a document by ID<br>app.patch(&#39;/documents/:id&#39;, async (req, res) =&gt; {<br>  const id = req.params.id;<br>  const updates = req.body;<br>  try {<br>    const result = await collection.updateOne(<br>      { _id: ObjectId(id) },<br>      { $set: updates }<br>    );<br>    if (result.matchedCount === 1) {<br>      res.status(200).send(&#39;Document updated&#39;);<br>    } else {<br>      res.status(404).send(&#39;Document not found&#39;);<br>    }<br>  } catch (err) {<br>    res.status(500).send(&#39;Error updating document&#39;);<br>  }<br>});<br><br>app.listen(port, () =&gt; {<br>  console.log(`Server running on http://localhost:${port}`);<br>});</pre><h4>2. Testing the Endpoints with Postman</h4><p><strong>POST Request: Create a New Document</strong></p><ol><li>Open Postman.</li><li>Create a new request.</li><li>Set the request method to POST.</li><li>Enter the URL: <a href="http://localhost:3000/documents.">http://localhost:3000/documents.</a></li><li>In the <strong>Body</strong> tab, select <strong>raw</strong> and <strong>JSON</strong> format.</li><li>Provide the JSON data for the new document. For example:</li></ol><ul><li>{ &quot;name&quot;: &quot;Jane Doe&quot;, &quot;email&quot;: &quot;jane.doe@example.com&quot; }</li></ul><p>7. Click <strong>Send</strong>. You should receive a response with the newly created document’s _id.</p><p><strong>DELETE Request: Remove a Document by ID</strong></p><ol><li>Open Postman.</li><li>Create a new request.</li><li>Set the request method to DELETE.</li><li>Enter the URL: http://localhost:3000/documents/{id}, replacing {id} with the document’s _id.</li><li>Click <strong>Send</strong>. You should receive a response indicating whether the document was successfully deleted.</li></ol><p><strong>PATCH Request: Update a Document by ID</strong></p><ol><li>Open Postman.</li><li>Create a new request.</li><li>Set the request method to PATCH.</li><li>Enter the URL: http://localhost:3000/documents/{id}, replacing {id} with the document’s _id.</li><li>In the <strong>Body</strong> tab, select <strong>raw</strong> and <strong>JSON</strong> format.</li><li>Provide the JSON data for the updates. For example:</li></ol><p>{ &quot;email&quot;: &quot;jane.newemail@example.com&quot; }</p><p>7. Click <strong>Send</strong>. You should receive a response indicating whether the document was successfully updated.</p><h4>3. Conclusion</h4><p>Handling POST, DELETE, and PATCH requests is essential for interacting with MongoDB documents through a RESTful API. By following the steps outlined above, you can create, update, and delete documents in MongoDB using Node.js and Express. Testing these operations with Postman allows you to ensure that your API endpoints work correctly and handle data as expected.</p><p>Feel free to customize and expand this basic setup to fit your application’s needs and to add more advanced features such as validation, authentication, and error handling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a40eb38f6de8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Postman to Find Single Documents in MongoDB]]></title>
            <link>https://medium.com/@saranipeiris17/using-postman-to-find-single-documents-in-mongodb-347fce32d94d?source=rss-c804abf0832b------2</link>
            <guid isPermaLink="false">https://medium.com/p/347fce32d94d</guid>
            <dc:creator><![CDATA[Sarani Peiris]]></dc:creator>
            <pubDate>Fri, 23 Aug 2024 11:11:19 GMT</pubDate>
            <atom:updated>2024-08-23T11:11:19.758Z</atom:updated>
            <content:encoded><![CDATA[<p>In this guide, we’ll walk through a basic scenario of using Postman to interact with a MongoDB database through a RESTful API. This example will cover setting up a simple Node.js and Express server that connects to MongoDB and provides an endpoint to fetch a single document. We’ll then use Postman to test this endpoint.</p><h4>1. Set Up Your Node.js and Express Application</h4><p><strong>Step 1: Initialize the Project</strong></p><p>Create a new directory for your project and initialize it with npm:</p><pre>mkdir mongodb-postman-demo<br>cd mongodb-postman-demo<br>npm init -y</pre><p><strong>Step 2: Install Required Packages</strong></p><p>Install Express and the MongoDB driver:</p><pre>npm install express mongodb</pre><p><strong>Step 3: Create the Server</strong></p><p>Create a file named server.js:</p><pre>const express = require(&#39;express&#39;);<br>const { MongoClient, ObjectId } = require(&#39;mongodb&#39;);<br><br>const app = express();<br>const port = 3000;<br><br>const uri = &#39;mongodb://localhost:27017&#39;;<br>const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });<br><br>app.use(express.json());<br><br>// Connect to MongoDB<br>client.connect().then(() =&gt; {<br>  console.log(&#39;Connected to MongoDB&#39;);<br>}).catch((err) =&gt; {<br>  console.error(&#39;Failed to connect to MongoDB&#39;, err);<br>});<br><br>// Route to find a single document by ID<br>app.get(&#39;/documents/:id&#39;, async (req, res) =&gt; {<br>  const id = req.params.id;<br>  const database = client.db(&#39;testdb&#39;);<br>  const collection = database.collection(&#39;testcollection&#39;);<br><br>  try {<br>    const document = await collection.findOne({ _id: ObjectId(id) });<br>    if (document) {<br>      res.json(document);<br>    } else {<br>      res.status(404).send(&#39;Document not found&#39;);<br>    }<br>  } catch (err) {<br>    res.status(500).send(&#39;Error fetching document&#39;);<br>  }<br>});<br><br>app.listen(port, () =&gt; {<br>  console.log(`Server running on http://localhost:${port}`);<br>});</pre><h4>2. Insert Sample Data into MongoDB</h4><p>To test the API, you need some sample data in your MongoDB collection. You can use the MongoDB shell or a GUI tool like MongoDB Compass to insert a document:</p><pre>use testdb<br>db.testcollection.insertOne({<br>  name: &#39;John Doe&#39;,<br>  email: &#39;john.doe@example.com&#39;<br>});<br><br>Take note of the _id field of the inserted document; you will need this for testing.</pre><h4>3. Test the API with Postman</h4><p><strong>Step 1: Open Postman</strong></p><p>Open Postman on your computer.</p><p><strong>Step 2: Create a New Request</strong></p><ol><li>Click on the <strong>New</strong> button or the <strong>+</strong> tab to open a new request.</li><li>Set the request method to GET.</li><li>Enter the URL of your endpoint. For example, if you inserted a document with _id 60d21b4667d0d8992e610c85, the URL would be <a href="http://localhost:3000/documents/60d21b4667d0d8992e610c85.">http://localhost:3000/documents/60d21b4667d0d8992e610c85.</a></li></ol><p><strong>Step 3: Send the Request</strong></p><p>Click the <strong>Send</strong> button. If everything is set up correctly, you should see the JSON representation of the document returned in the response body.</p><p><strong>Step 4: Review the Response</strong></p><p>The response should include the document details, such as:</p><pre>{<br>  &quot;_id&quot;: &quot;60d21b4667d0d8992e610c85&quot;,<br>  &quot;name&quot;: &quot;John Doe&quot;,<br>  &quot;email&quot;: &quot;john.doe@example.com&quot;<br>}</pre><p>If the document is not found, you’ll receive a 404 status with the message “Document not found.” If there’s an error, a 500 status code with “Error fetching document” will be returned.</p><h4>4. Conclusion</h4><p>Using Postman to interact with your MongoDB database via a RESTful API is a straightforward process. By following these steps, you can set up a Node.js and Express server, create an endpoint to fetch documents, and use Postman to test and verify your API.</p><p>This approach allows you to test and debug your API endpoints effectively, ensuring that your application behaves as expected when retrieving single documents from MongoDB.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=347fce32d94d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>