<?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 PUVVADA BHARGAVI on Medium]]></title>
        <description><![CDATA[Stories by PUVVADA BHARGAVI on Medium]]></description>
        <link>https://medium.com/@saibhargavi.puvvada?source=rss-cb55138d3fa7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ZF9QFxY1EsbnU1Cj</url>
            <title>Stories by PUVVADA BHARGAVI on Medium</title>
            <link>https://medium.com/@saibhargavi.puvvada?source=rss-cb55138d3fa7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 11:13:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saibhargavi.puvvada/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[Mongoose library : MongoDB made easy]]></title>
            <link>https://medium.com/@saibhargavi.puvvada/mongoose-library-mongodb-made-easy-83d944a00bdb?source=rss-cb55138d3fa7------2</link>
            <guid isPermaLink="false">https://medium.com/p/83d944a00bdb</guid>
            <dc:creator><![CDATA[PUVVADA BHARGAVI]]></dc:creator>
            <pubDate>Sun, 05 Nov 2023 20:35:59 GMT</pubDate>
            <atom:updated>2023-11-05T20:35:59.995Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mongoose library : MongoDB made easy</h3><p><strong>Mongoose library</strong> — It is a light weight library that is built on top of mongoDB and it abstracts so many low level details of MongoDB making it easy for developer to perform CRUD operations on MongoDB collections and it helps them to focus more on business logic than focusing on database level operations, syntax, errors.</p><p><strong>How to integrate it into our application?</strong></p><p><strong>Install MongoDB by following the steps mentioned in the below link: </strong><br><a href="https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-os-x/">https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-os-x/</a></p><p><strong>Install mongoose library by running this syntax:</strong></p><blockquote><strong>npm install mongoose</strong></blockquote><p>After installing the mongoDB we have to <strong><em>start the MongoDB server</em></strong> for storing and managing the data by running this syntax:</p><blockquote><strong>mongod</strong></blockquote><p>Hurrah!! We have successfully installed <strong>mongoDB</strong> and <strong>mongoose. </strong>So let’s understand the different concepts of mongoose library together.</p><p><strong>There are some advantages in using mongoose library:</strong></p><p>It is an object data modelling library which allows us to create a <strong>schema</strong> and <strong>model</strong> for the collection, middleware and validations for the schema easily.</p><p><strong>Collections: </strong>It is nothing but a database where we store collection of documents. Collection is similar to table in RDBMS.</p><p><strong>Document: </strong>It is a single record that is stored into the collection. It is similar to record or row in RDBMS.</p><p><strong>Schema — </strong>It defines the structure of the document that we want to store in database collection. We specify which kind of data can be stored in a collection and data type for each field and what kind of validations(restrictions) that we want to perform on the data.<br><strong>Ex for schema creation:</strong></p><pre>const budgetSchema = new mongoose.Schema({<br>  amount: {<br>    type: Number,<br>    required: true,<br>    trim: true,<br>    validate(value) {<br>      if (value == 0) {<br>        throw &#39;Amount cannot be Zero&#39;;<br>      } else if (value &lt; 0) {<br>        throw &#39;Amount cannot be negative&#39;;<br>      }<br>    },<br>  },<br>  startDate: {<br>    type: Date,<br>    required: true,<br>  },<br>  endDate: {<br>    type: Date,<br>    required: true,<br>  },<br>});</pre><p>Here we are creating a <strong>budgetSchema</strong> with these fields — <strong>amount, startDate, endDate </strong>and for all the variables we are specifying what kind of values that these fields will accept and we are marking them as “required” so if we try to insert a document without these fields mongoose will throw an error when performing the validations and for amount field we are specifying the extra validations by using validate() method.</p><p><em>MongoDB provides </em><strong><em>Flexible schema </em></strong><em>which means it will allow us to store the data into DB without specifying the schema because the main difference between RDBMS record and MongoDB document is it allows to store different data with different datatypes in each document. It is not necessary to have same data in each document of collection</em></p><p><strong>Model: </strong>It provides interface for performing different operations on the collections and for querying the data of the collection. We have to pass the above created schema to the model constructor along with the name of the collection</p><pre>const budgetModel = mongoose.model(&#39;Budget&#39;, budgetSchema);</pre><p>Here we are creating a <strong>budgetModel</strong> by passing <strong>budgetSchema</strong> and collection name as “<strong>Budget</strong>”. So a collection with name “<strong>Budgets</strong>” will be created in the specified database. <br>Mongoose will consider the plural form of collection name while creating it in database.<br><strong>For ex:</strong> In the above example we are passing collection name as “Budget” but it will consider “Budgets”.</p><p><strong>Middleware: </strong>This concept helps us to perform certain operations at a specific point in the document and query life cycle like before storing the data into DB we want to perform certain operations like hashing the sensitive data like passwords or validating the data or removing data.</p><p>Mongoose supports two types of middleWares — document middleWares, query middleWares.</p><p>we can specify the middleware logic by using <strong>pre</strong> and <strong>post</strong> methods of mongoose:<br><strong>Ex:</strong></p><pre>const budgetSchema = new mongoose.Schema({<br>  amount: {<br>    type: Number,<br>    required: true,<br>    trim: true<br>  },<br>  startDate: {<br>    type: Date,<br>    required: true,<br>  },<br>  endDate: {<br>    type: Date,<br>    required: true,<br>  },<br>});<br><br>budgetSchema.pre(&#39;validate&#39;,function (next) {<br>  if (this.amount === 0) {<br>    next(new Error(&#39;Amount cannot be Zero&#39;));<br>  } else if (this.amount &lt; 0) {<br>    next(new Error(&#39;Amount cannot be negative&#39;));<br>  } else {<br>    next();<br>  }<br>});</pre><p>When creating the budget schema we have applied the constraints by specifying the validate() function but here with the help of middleware we have moved that logic to middleware. So every time we store a document it will be validated against these constraints.</p><p>What is the use of <strong>next() </strong>in middleware?<br>It is a callback which will be called after executing the current middleware and moves the controller to the next middleware specified in the chain. If the current middleware throws any error mongoose will recognise and skip all the remaining middlewares and execute error handling middleware.</p><p>Awesome now we have defined schema and model for our Budget collection. What’s next 🤔</p><p><strong>Connecting to MongoDB in Node JS application using Mongoose library:</strong></p><p>We can connect to different mongoDB deployments provided by mongoDB Atlas, cloud deployments or local deployment. Lets try to understand how to connect to local MongoDB deployment running on the localhost with default port.</p><p>Use this syntax to connect to local deployment:</p><pre>const mongoose = require(&#39;mongoose&#39;)</pre><pre>mongoose.connect(&#39;mongodb://localhost:27017/database_name&#39;) // localhost = 127.0.0.1 sometimes localhost will not map to this default value so replace it with this 127.0.0.1<br>  .then(() =&gt; console.log(&#39;Connected!&#39;))</pre><p><strong>connect </strong>method of mongoose is used to connect to the mongoDB database .<br><strong>database_name</strong> is the name of the database to which we want to connect to.<br><strong>27017 — </strong>default <strong>port</strong> on which the local mongoDB deployment will be running.<br><strong>callback function</strong> — inside then we can pass a call back function which will be executed after successfully connecting to the database.</p><p><strong>How to use this model and perform the CRUD operations on our collection?</strong></p><p><strong>Create Data:</strong></p><ol><li>Create an instance for budget model with the data that you want to store into DB</li><li>Use methods provided by mongoose to store the data into DB</li></ol><pre>//step 1 : create an instance of BudgetModel<br>const budget = new budgetModel({<br>  amount: 5000,<br>  startDate: new Date(),<br>  endDate: new Date(),<br>});<br><br>//step 2 : use save method of mongoose library to store the data into DB<br>await budget.save().then(() =&gt; {<br>        console.log(&quot;success&quot;);<br>      })<br>      .catch(error =&gt; console.log(&quot;error:&quot;,error));</pre><p><strong>Read Data:<br></strong>Use find method of mongoose library to get all the data from the budget model.</p><pre>await budgetModel.find()<br>     .then(budgetList =&gt; console.log(&quot;budget list:&quot;, budgetList))<br>     .catch(error =&gt; console.log(&quot;error:&quot;,error));</pre><p>Use <strong>findById </strong>method<strong> </strong>to get the details of specific budget.</p><pre>await budgetModel.findById({_id: budgetId})<br>     .then(budgetDetails =&gt; console.log(&quot;budget Details:&quot;, budgetDetails))<br>     .catch(error =&gt; console.log(&quot;error:&quot;,error));</pre><p><strong>Update Data:</strong></p><pre>const updateDetails = {<br> amount: 3000 <br>}; <br>await budgetModel.updateOne({_id: budgetId}, {$set: updateDetails})<br> .then(res =&gt; console.log(&quot;res:&quot;, res))<br> .catch(error =&gt; console.log(&quot;error:&quot;,error));</pre><ul><li>There are some other methods available like <strong>updateMany</strong>, <strong>findOneAndUpdate</strong>.</li></ul><p><strong>Delete Data:</strong></p><p>Use <strong>findOneAndRemove </strong>method to delete the specific budget.</p><pre>await budgetModel.findOneAndRemove({_id: budgetId})<br>     .then(res =&gt; console.log(&quot;res:&quot;, res))<br>     .catch(error =&gt; console.log(&quot;error:&quot;,error));</pre><ul><li>We can use <strong>deleteMany</strong> method to delete multiple records of collection based on the condition.</li></ul><p><strong>Disconnecting from the MongoDB using mongoose library:</strong></p><pre>await mongoose.disconnect()<br>.then(() =&gt; console.log(&quot;Successfully disconnected from the database&quot;))<br>     .catch(error =&gt; console.log(&quot;error:&quot;,error));</pre><p>I hope this blog helped you to understand some of the concepts of mongoose. <br>Here we have gone through some of the concepts and some methods of mongoose library and you can continue learning the other concepts in the mongoose docs — <a href="https://mongoosejs.com/docs/">https://mongoosejs.com/docs/</a></p><p>Happy Learning😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83d944a00bdb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Mystery of JavaScript: It’s inner workings]]></title>
            <link>https://medium.com/@saibhargavi.puvvada/unlocking-the-mystery-of-javascript-its-inner-workings-7736468e5615?source=rss-cb55138d3fa7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7736468e5615</guid>
            <dc:creator><![CDATA[PUVVADA BHARGAVI]]></dc:creator>
            <pubDate>Fri, 03 Nov 2023 10:58:49 GMT</pubDate>
            <atom:updated>2023-11-06T09:39:49.267Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Unlocking the Mystery of JavaScript: It’s inner workings</strong></p><p>We are writing the javascript code and running it but wonder how things are working behind the scenes 🤔</p><p>Yeah I am also curious like you so lets dive deep into it and try to understand the concepts together😃</p><p><strong>Javascript Run time Environment:</strong></p><p>It is an environment that provides a set of components that are required to execute the JS code</p><p>Whether you are running the javascript code in browser or in server side the basic structure of run time environment will be same with some differences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*6_g_JTED1HsrxgMdbRkfig.jpeg" /><figcaption><strong>Browser Javascript runtime environment</strong></figcaption></figure><p><strong>Javascript Engine:</strong> Engine that is responsible for running the javascript code and we have different javascript engines available</p><p><strong>Ex:</strong> Google chrome uses v8 engine, FireFox uses spider monkey, Safari uses JavascriptCore</p><p>And Modern JS engines like v8, spider monkey use <strong>Just-In-time</strong> compilation</p><p><strong>Just-In-time Compilation: </strong>The source code will be converted into machine code(code which can be understandable by the machine) and it will be executed immediately. So it speeds up the javascript execution when compared to pure compilation and interpretation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*kpFTHvwmyVK15cpVnZy6vA.jpeg" /></figure><ul><li>Internally when we give the javascript code to the browser it parses the code and checks for syntax errors and if there are no any errors it generates the Abstract syntax tree.</li><li>This tree will be compiled using JIT compiler and machine code will be created.</li><li>Modern JS engines initially creates unoptimised version of machine code to start the execution as soon as possible and behind the scenes it will optimise the code and compiles it continuously.</li></ul><p><strong>Call Stack: </strong>It is an environment where the javascript code will be executed and it takes care of in which order the functions should be executed and handles the execution context of each and every function.</p><p><strong>Execution context:</strong> It is a environment where JS code will be executed and all the variables, arguments that are passed to the function and all the inner functions definition will be stored in the execution context.</p><p><strong>Two types of execution context:</strong></p><ol><li><strong>Global Execution context:</strong> All the top level code which is not present in any function will be stored in the Global execution context and there will be only one global execution context in any code.</li><li><strong>Function Execution context:</strong> For each and every function a new function execution context will be created and all the variables, arguments, functions present in that function will be stored inside it</li></ol><p><strong>Execution context consists of 3 components:</strong></p><ul><li><strong>Variable Environment: </strong>It contains the variable object and outer environment reference. Variable object contains variables, arguments object and function definitions.</li><li><strong>Scope chain</strong>: It decides the scope in which variables, functions can be accessed.</li><li><strong>this</strong>: This keyword will contain reference to the object which called the function</li></ul><p><strong>For every function Execution context will be created in two phases:</strong></p><ol><li><strong>Creation phase</strong> — JS engine will scan the entire code and creates Global and function execution context, creates the scope chain and allocates memory for all the variables and functions in memory heap</li></ol><p>For all the variables that are created-</p><ul><li>Using <strong>var</strong> keyword memory will be created and initialised with <strong>undefined</strong> value</li><li>Using <strong>let</strong> and <strong>const </strong>keyword memory will be created and remains uninitialised</li></ul><p><strong>For Regular functions</strong> memory will be created and initialised with function definition</p><p>Creation phase uses the concept called “<strong>Hoisting</strong>” which describes which variables and functions can be accessed even before declaring them.</p><p><strong>In Hoisting —</strong></p><ul><li>Variables created using <strong>let</strong> or <strong>const</strong> will enter into TDZ(Temporal Dead Zone) which means if we try to access the variables before declaring it will throw reference error.</li><li>Variables created using <strong>var</strong> keyword will be hoisted to the top and will be initialised with <strong>undefined</strong> value. So if we try to access it before declaring it wont throw any error but will give <strong>undefined</strong> as value</li></ul><pre>console.log(itemName)<br>var itemName = &quot;Bat&quot;<br>console.log(itemPrice)<br>let itemPrice = 500<br>console.log(companyName)<br>const companyName = &quot;CompanyName&quot;</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjR6mp3TZKxeN0xNvMf7Vg.gif" /></figure><ul><li><strong>Regular</strong> <strong>functions</strong> will be hoisted to the top so we can access the functions before declaring it.</li></ul><pre>var itemName = &quot;Bat&quot;<br>displayItem(itemName)<br>function displayItem(itemName){<br>  console.log(&quot;Item Name:&quot;,itemName)<br>}</pre><p>output: Here we are able to access the function even before it is definition</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Rcotik1LINjZ4Z08-5k1Q.gif" /></figure><p>Scope chain will be created during the creation phase of execution context<br><strong>Scope Chain — </strong>This concept specifies inner functions will have access to which variables, functions that are declared in outer scopes. This will be used for the <strong>variable resolution</strong> during the execution phase.</p><p>Here:</p><ul><li><strong>Global Execution context</strong> will have access to the variables and functions that are declared in global scope</li><li><strong>Top level functions</strong> will have its own variable environment and also have access to the global scope</li><li><strong>Inner functions</strong> will have their own variable environment and also have access to all the variables, functions that are present in parent execution context and all the way upto global scope</li></ul><pre>//Global scope<br>var itemName = &quot;Bat&quot;<br>console.log(&quot;Item Name in global scope:&quot;,window.itemName)<br><br>// Top level function<br>function displayItemDetails(itemName){<br>  console.log(&quot;Item Name in function scope:&quot;,itemName)<br>  var companyName = &#39;CompanyName&#39;<br><br>  // Inner function<br>  function displayDetailsAlongWithPriceAndCompanyName(itemName){<br>    console.log(&quot;Item name in inner function scope:&quot;,itemName)<br>    console.log(&quot;company name in inner function scope:&quot;, companyName)//will have access to variables declared in outer scope<br>    console.log(&quot;price:&quot;, 500)<br>  }<br>  displayDetailsAlongWithPriceAndCompanyName(itemName)<br>}<br><br>displayItemDetails(itemName)</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C9oaQfpB5duxLt_97DjUMQ.gif" /></figure><p><strong>2. Executing phase</strong> — JS engine will scan the entire code to assign the value of variable object variables and executes the code line by line</p><p><strong>This keyword</strong>: The value of the <strong>this </strong>keyword in JavaScript is determined during the execution phase and depends on how the function is invoked.</p><ul><li>In <strong>Global scope</strong> this keyword points to <strong>window</strong> object (<strong>global</strong> object in Node JS)</li><li><strong>Top-level regular functions:</strong> In non-strict mode, when a regular (non-arrow) function is invoked in the top-level scope, <strong>this</strong> points to the global object (window in a browser). In strict mode, this will give <strong>undefined</strong></li><li><strong>Inner regular functions:</strong> The <strong>this</strong> value in an inner regular function depends on how it&#39;s invoked. If it&#39;s called as a method of an object, <strong>this</strong> typically refers to that object. In other cases, it may still refer to the global object (window) or will be undefined in strict mode.</li><li><strong>Arrow functions: </strong>Arrow functions inherit the this value from their containing (parent) function or lexical environment.<br>- When used within a regular function, the <strong>this</strong> in an arrow function refers to the same <strong>this</strong> as in the containing function.<br>- If we have the arrow function at the top level, this will point to the window object in non-strict mode and undefined in strict mode</li></ul><pre>var itemName = &quot;Bat&quot;<br>//global scope this will point to window object<br>console.log(&quot;********&quot;)<br>console.log(&quot;Item Name in global scope:&quot;,this)<br><br>// Top level function<br>function displayItemDetails(itemName){<br>  console.log(&quot;Item Name in function scope:&quot;,this.itemName) // this will point to window object<br>  var companyName = &#39;CompanyName&#39;<br>  // Inner Regular function<br>  function displayItemNameRegularFunction(){<br>    console.log(&quot;:::::In inner regular function scope:::::&quot;)<br>    console.log(&quot;Item name:&quot;,this.itemName) // this will point to window object<br>  }<br>  displayItemNameRegularFunction()<br><br>  // Inner Regular function<br>  function displayItemNameWhenCalledOnObject(){<br>    console.log(&quot;:::::In inner regular function scope called with an object:::::&quot;)<br>    console.log(&quot;Item name:&quot;,this.itemName) // this will point to the object which called this function<br>    //Inner arrow function called in outer regular function<br>    var displayItemNameWhenCalledOnObjectArrowFunction = () =&gt; {<br>      console.log(&quot;:::::In inner arrow function scope called with an object and inside regular function:::::&quot;)    <br>      console.log(&quot;Item name:&quot;,this.itemName) // this will point to parent function this object <br>    }<br>    displayItemNameWhenCalledOnObjectArrowFunction()<br>  }<br><br>  const itemObj = {itemName:&#39;box&#39;, display: displayItemNameWhenCalledOnObject }<br><br>  itemObj.display()<br>  <br>  // Inner Arrow function<br>  <br>  var displayItemNameArrowFunction = () =&gt; {<br>    console.log(&quot;:::::In inner arrow function scope:::::&quot;)    <br>    console.log(&quot;Item name:&quot;,this.itemName) // this will point to parent function this object which indireclty points to window object<br>  }<br>  displayItemNameArrowFunction()<br><br> var displayItemNameWhenCalledOnObjectArrowFunction = () =&gt; {<br>    console.log(&quot;:::::In inner arrow function scope called with an object:::::&quot;)    <br>    console.log(&quot;Item name:&quot;,this.itemName) // this will point to parent function this object which indireclty points to window object<br>  }<br> <br>  const itemObjForArrowFunction = {itemName:&#39;ball&#39;, display: displayItemNameWhenCalledOnObjectArrowFunction }<br><br>  itemObjForArrowFunction.display()<br>}<br><br>// top level Arrow function<br>  <br>var displayItemNameArrowFunction = () =&gt; {<br>  console.log(&quot;:::::In top level arrow function scope:::::&quot;)<br>  console.log(&quot;this:&quot;,this)<br>  console.log(&quot;Item name:&quot;,this.itemName) // this will point to window object<br>}<br><br>displayItemNameArrowFunction()<br>displayItemDetails()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37un8RR-Z1caiiFC9g_b6g.gif" /></figure><p>To test the same code in strict mode add “use strict” in first line<strong><br>Event Loop:</strong></p><p>Now we have understood how the execution context is created for all the functions present in the code now let’s understand how the JS code and its events will be executed.</p><p>JS engine uses a concept called <strong>‘Event loop’ </strong>when we run the JS code it follows the below steps:</p><ol><li>Global execution context will be created</li><li>For every new function a separate Function execution context will be created</li><li>During the execution phase of every execution context if there are any asynchronous functions like timer functions, network calls, DOM related actions those will be pushed into web API and handled by event loop</li></ol><p>4. The events that are pushed into web Api will be running behind the scenes and the other rest of the code will be executed in the call stack</p><p>5. If the events present in the web API are handled they will be moved into callback queue. Callback queue will contains the callbacks which are ready for execution and there are two different call back queues — task queue, micro task queue</p><ul><li>task queue — will handle less time sensitive tasks like setTimeout, setTimeInterval callbacks</li><li>micro task queue — will handle high priority and time sensitive tasks like promise related tasks and async/await tasks. So these tasks will be executed before executing the task queue</li></ul><p>6.Until the call stack is empty the callbacks which are stored in callback queue will not be executed once the call stack is empty event loop will bring the every callback into call stack one by one and it will execute them</p><p>7. Once all the callbacks are successfully executed they will be removed from the call stack and once all the code is executed successfully in the end global execution context will also be removed</p><p>See the below video to understand how event loop works with help of visualiser</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X5uS8tJluDfw-bgo5yXpLQ.gif" /></figure><p>To understand more about event loop try this visualiser and expirement different concepts<br><a href="https://www.jsv9000.app/">https://www.jsv9000.app/</a></p><p>I hope this blog helped you to understand the basics of how javascript works behind the scenes and continue exploring more on this.</p><p>Happy Learning😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7736468e5615" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>