<?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"><channel><title><![CDATA[Untitled Publication]]></title><description><![CDATA[Untitled Publication]]></description><link>https://blog.paulasantamaria.com</link><generator>RSS for Node</generator><lastBuildDate>Thu, 12 Nov 2026 13:56:22 GMT</lastBuildDate><atom:link href="https://blog.paulasantamaria.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Bun 1.0 setup for Windows with VSCode and Docker]]></title><description><![CDATA[Integrate Bun into your development workflow: Code, forward ports, & debug!]]></description><link>https://blog.paulasantamaria.com/bun-10-setup-for-windows-with-vscode-and-docker</link><guid isPermaLink="true">https://blog.paulasantamaria.com/bun-10-setup-for-windows-with-vscode-and-docker</guid><category><![CDATA[Bun]]></category><category><![CDATA[Docker]]></category><category><![CDATA[Windows]]></category><category><![CDATA[Visual Studio Code]]></category><dc:creator><![CDATA[Paula Santamaría]]></dc:creator><pubDate>Sun, 24 Sep 2023 14:00:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1695425743425/7d7f70b9-e53a-46cb-8381-c238d71bd17f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I’ve been meaning to try Bun for a while now, and after the release of v1.0 I decided to make time for it. But when I finally sat down and started reading the docs, I realized it doesn’t run on Windows <a target="_blank" href="https://github.com/oven-sh/bun/issues/43">just yet</a>.</p>
<p>However, I saw the documentation to run it with Docker, and I thought it could be a cool alternative. After a few hours of research and experimentation, here we are!</p>
<p>By following this guide, you will be able to seamlessly integrate Bun into your development workflow on a Windows machine using VSCode. We will see how to:</p>
<ul>
<li><p>Develop a project with Bun using the same VSCode setup you use every day.</p>
</li>
<li><p>Forward ports so you can test your Websites and APIs in your local browser.</p>
</li>
<li><p>And even Debug with proper breakpoints and everything!</p>
</li>
</ul>
<h2 id="heading-what-youll-need">What you'll need</h2>
<p>Before we get started, make sure you have the following tools installed:</p>
<ul>
<li><p>Docker</p>
</li>
<li><p>VSCode</p>
</li>
<li><p>Dev Containers VSCode extension</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695425989282/52d70b09-f51b-440d-8501-16455fc37848.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-how-it-works">How it works</h2>
<p>Through the Dev Containers extension, we’re going to use a container as a development environment.</p>
<p>The Docker image we will use for our container is based on the official Docker image <code>oven/bun:latest</code>. This means that once our container is up and running, we will have immediate access to Bun.</p>
<p>The files in our project will be automatically mounted from the local file system. Therefore, while the project will run in the container, the source code will remain updated on our local machine.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695426034886/12e2c096-b146-4fa0-b903-adec52b24027.png" alt class="image--center mx-auto" /></p>
<blockquote>
<p>Image borrowed from <a target="_blank" href="http://code.visualstudio.com">code.visualstudio.com</a></p>
</blockquote>
<h2 id="heading-setting-up-the-dev-container">Setting up the Dev Container</h2>
<p>Let’s create a directory and open it with VSCode:</p>
<pre><code class="lang-bash">&gt; mkdir bunproject
&gt; code bunproject
</code></pre>
<p>Create a new Dockerfile in the project directory with the following content:</p>
<pre><code class="lang-docker"><span class="hljs-comment"># Use the latest version of the bun image as the base image</span>
<span class="hljs-keyword">FROM</span> oven/bun:latest

<span class="hljs-comment"># Set `DEVCONTAINER` environment variable to help with orientation</span>
<span class="hljs-keyword">ENV</span> DEVCONTAINER=true
</code></pre>
<p>Now let’s run our Dev Container:</p>
<ol>
<li><p>Open the command palette in VSCode by pressing <code>Ctrl + Shift + P</code> and run the command "Dev Containers: Open folder in container".</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695426161922/0412ecdc-1fe9-492e-93e4-fb5d3711a179.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Then, choose the option to create the container using our Dockerfile.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695426172259/874b6e0f-266c-44f0-a43d-3762b1900954.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>When prompted with the "Select Features" option, just press OK without selecting any additional features.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695426191720/a0f553a9-2fb6-4515-825d-10083a6ec5d6.png" alt class="image--center mx-auto" /></p>
</li>
</ol>
<p>VSCode will reload and open your project in a dev container. You should also see a new directory in your project called <code>.devcontainer</code>. Within it, there should be a <code>devcontainer.json</code> file including our dev container settings.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695426217631/715a841b-4902-4654-a1fb-09db4fd06aa8.png" alt class="image--center mx-auto" /></p>
<p>If you’ve reached this point, you are already running a project within the container as a dev environment. But it’s empty! So let's keep going.</p>
<h2 id="heading-setting-up-the-project-with-bun">Setting up the project with Bun</h2>
<p>Since our container was created using Bun's official Docker image, Bun is already installed and ready to use.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695426240054/e505a250-90e0-4199-90a6-f37c8a6ced85.png" alt class="image--center mx-auto" /></p>
<p>Follow these steps to set up your project:</p>
<ol>
<li><p>Open VSCode’s integrated terminal and initialize a Bun project by running the following command:  </p>
<pre><code class="lang-bash">&gt; bun init
</code></pre>
</li>
<li><p>Install any necessary dependencies using bun’s package manager:</p>
<pre><code class="lang-bash">&gt; bun install chalk
</code></pre>
</li>
<li><p>Update the <code>index.ts</code> file in VSCode with your desired code. For example:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> chalk <span class="hljs-keyword">from</span> <span class="hljs-string">'chalk'</span>;
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello via <span class="hljs-subst">${chalk.yellow.bold(<span class="hljs-string">'Bun'</span>)}</span>!`</span>);
</code></pre>
</li>
<li><p>Run the project with Bun using the command:</p>
<pre><code class="lang-bash">&gt; bun --hot index.ts
</code></pre>
</li>
</ol>
<blockquote>
<p>The <code>--hot</code> flag enables hot reload, allowing you to see changes in real-time while developing.</p>
</blockquote>
<p>✅ Done! You are now developing with Bun in Windows.</p>
<p>But there are a couple more cool things we can do with these tools. Let's take a look.</p>
<h2 id="heading-forwarding-ports">Forwarding ports</h2>
<p>If you're building an HTTP server and want to test your API from your browser, you can forward ports from the container to your local environment. Here's how:</p>
<ol>
<li><p>Write a simple server in the <code>index.ts</code> file, specifying the desired port:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">const</span> server = Bun.serve({
   port: <span class="hljs-number">3000</span>,
   fetch(request) {
     <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(<span class="hljs-string">"Welcome to Bun!"</span>);
   },
});

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Listening on localhost:<span class="hljs-subst">${server.port}</span>`</span>);
</code></pre>
</li>
<li><p>Open the <code>.vscode/devcontainer.json</code> file and add the following code:</p>
<pre><code class="lang-json">{
   <span class="hljs-comment">// Other props ...</span>

   <span class="hljs-attr">"forwardPorts"</span>: [
       <span class="hljs-number">3000</span>
   ]
}
</code></pre>
</li>
<li><p>Rebuild the dev container by opening the command palette and running the "Dev Containers: Rebuild Container" command.</p>
</li>
<li><p>Once the dev container is running again, you should see your forwarded port in the “Ports” view at the bottom:</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695426443731/ffb8745a-789f-4daa-b975-23925b12e296.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Start the server using Bun:</p>
<pre><code class="lang-bash">&gt; bun --hot index.ts
</code></pre>
</li>
<li><p>Open your browser and navigate to <a target="_blank" href="http://localhost:3000">http://localhost:3000</a> to test your API.</p>
</li>
</ol>
<h2 id="heading-debugging">Debugging</h2>
<p>With this setup you can even debug bun, with breakpoints and everything!</p>
<p>Follow these steps to set it up:</p>
<ol>
<li><p>Install the official extension “Bun for Visual Studio Code”.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695426505153/413710eb-f210-45c2-9cf4-dc0b638d188c.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Now open the command palette and search for the option “Debug: Add Configuration".</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695426584335/6ff36ea0-b204-4b89-a7f3-8a99df73bac9.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>When prompted to select a Debugger, choose “Bun” (you should see this option after installing the extension in step 1).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695426602647/8fbbf406-cb8f-48d9-993a-b3c1baf9bead.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>You should now see a new directory and file <code>.vscode/launch.json</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695426628519/35535b51-8020-4c01-bfb3-95f6d0510a50.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Open the Debug view, and make sure the current configuration is “Debug file”.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695426644312/9af0aa89-6628-4255-8878-cb6679f93cd6.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Finally, try setting a few breakpoints and press <code>F5</code> to start debugging!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695426656660/8008713f-7609-457a-876d-91a3b2455415.png" alt class="image--center mx-auto" /></p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I've been trying this setup for a week, and it feels great. You can even use Docker Compose to combine it with other services or databases! The only slightly annoying thing is having to run Docker for small apps and wait for the container to start. But overall, I think this is a fantastic option for people who want to try Bun on Windows right away.</p>
<p>It's also worth noting that you can use these tools to run other technologies with Dev Containers. In fact, the examples I used as inspiration for this post were for a Node.js dev container.</p>
<p>That’s it for now! Happy coding :)</p>
<hr />
<p><img src="https://www.typescriptgamified.com/_app/immutable/assets/banner-01-16795b9b.webp" alt /></p>
<p>Get my book: <a target="_blank" href="http://typescriptgamified.com">typescriptgamified.com</a></p>
]]></content:encoded></item><item><title><![CDATA[Debugging TypeScript projects with VSCode in 2023]]></title><description><![CDATA[A simple config for your Node.js and TypeScript projects to get debugging and auto-restarts working together in just a few minutes.]]></description><link>https://blog.paulasantamaria.com/debugging-typescript-projects-with-vscode-in-2023</link><guid isPermaLink="true">https://blog.paulasantamaria.com/debugging-typescript-projects-with-vscode-in-2023</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Visual Studio Code]]></category><dc:creator><![CDATA[Paula Santamaría]]></dc:creator><pubDate>Sun, 16 Apr 2023 17:19:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1681613762512/958139f0-113a-4a73-bc0b-5913e86c7bb0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I finally decided to invest some time in properly setting up a debugger for my Node + TS projects. <code>console.log</code> is cool and all, but it just wasn't cutting it anymore.</p>
<p>So, I've been reading documentation (plus so many GitHub issues), and trying different solutions, and I ended up with a config that I'm actually happy with!</p>
<p>Keep reading to learn how to:</p>
<ol>
<li><p>Create a project with Node.js and TypeScript.</p>
</li>
<li><p>Install a package (<code>ts-node-dev</code>) and configure it so it can run your project and auto-restart on save.</p>
</li>
<li><p>Configure the debugger in VSCode so it uses <code>ts-node-dev</code> to both enable the debugging of <code>.ts</code> files and provide auto-restarts.</p>
</li>
<li><p>Finally, stop relying on <code>console.log('here!')</code> to debug your code :D</p>
</li>
</ol>
<h2 id="heading-initialize-the-project">Initialize the project</h2>
<p>Create a directory for your project and initialize it:</p>
<pre><code class="lang-bash">mkdir ts-starter
<span class="hljs-built_in">cd</span> ts-starter
npm init -y
</code></pre>
<h2 id="heading-install-typescript">Install TypeScript</h2>
<p>Install TypeScript and the type definitions for node:</p>
<pre><code class="lang-bash">npm install typescript @types/node --save-dev
</code></pre>
<h2 id="heading-setup-your-tsconfig">Setup your tsconfig</h2>
<p>To create the <code>tsconfig.json</code> file, run the following command:</p>
<pre><code class="lang-bash">npx tsc --init
</code></pre>
<p>The default <code>tsconfig.json</code> generated should look something like this:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"compilerOptions"</span>: {
        <span class="hljs-attr">"target"</span>: <span class="hljs-string">"ES2016"</span>,
        <span class="hljs-attr">"module"</span>: <span class="hljs-string">"commonjs"</span>,
        <span class="hljs-attr">"esModuleInterop"</span>: <span class="hljs-literal">true</span>,
        <span class="hljs-attr">"forceConsistentCasingInFileNames"</span>: <span class="hljs-literal">true</span>,
        <span class="hljs-attr">"strict"</span>: <span class="hljs-literal">true</span>,
        <span class="hljs-attr">"skipLibCheck"</span>: <span class="hljs-literal">true</span> 
    }
}
</code></pre>
<h2 id="heading-install-ts-node-dev">Install ts-node-dev</h2>
<p>We’re going to hook up <code>ts-node-dev</code> with the VSCode debugger to get both the debugger and auto-restarts working!</p>
<p>Start by installing the package:</p>
<pre><code class="lang-bash">npm install ts-node-dev --save-dev
</code></pre>
<p>To quickly try it out, we can create a new script in the <code>package.json</code>:</p>
<pre><code class="lang-json"><span class="hljs-string">"scripts"</span>: {
    <span class="hljs-attr">"dev"</span>: <span class="hljs-string">"ts-node-dev --respawn src/index.ts"</span>
},
</code></pre>
<p>Now let’s write some code to run!</p>
<p>Create the <code>src</code> directory and add the following code:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// index.ts</span>

<span class="hljs-keyword">interface</span> Game {
  name: <span class="hljs-built_in">string</span>;
  genre: <span class="hljs-built_in">string</span>;
  platform: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">const</span> game: Game = {
  name: <span class="hljs-string">"Super Mario"</span>,
  genre: <span class="hljs-string">"Platformer"</span>,
  platform: <span class="hljs-string">"Nintendo"</span>,
};

<span class="hljs-built_in">console</span>.log(game);
</code></pre>
<blockquote>
<p>We’re adding some types so we can make sure the compiler is working properly.</p>
</blockquote>
<p>Finally, run the <code>dev</code> script from your terminal:</p>
<pre><code class="lang-bash">npm run dev
</code></pre>
<p>You should see something like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681610527820/e3bea4f7-11a9-4cf6-8026-0a84adb89f3a.png" alt class="image--center mx-auto" /></p>
<p>And finally, change the values in your <code>game</code> constant and save the file, to see the automatic restarts in action!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681610572334/bc2163d0-fe2b-4ba6-88c5-bde31300d645.gif" alt class="image--center mx-auto" /></p>
<p>Nice, we can see how the app auto-restarts after we make changes!</p>
<h2 id="heading-set-up-the-vscode-debugger">Set up the VSCode Debugger</h2>
<p>First, let’s generate a <code>launch.json</code> file. To do that:</p>
<ol>
<li><p>Open the command palette (<code>Ctrl</code> + <code>Shift</code> + <code>P</code> or <code>Cmd</code> + <code>Shift</code> + <code>P</code> on Mac) and select “Debug: Add Configuration”</p>
</li>
<li><p>On the next step, select <code>Node.js</code> for the Debugger</p>
</li>
</ol>
<p>You should get an auto-generated <code>launch.json</code> file, like this one:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"version"</span>: <span class="hljs-string">"0.2.0"</span>,
    <span class="hljs-attr">"configurations"</span>: [
        {
            <span class="hljs-attr">"type"</span>: <span class="hljs-string">"node"</span>,
            <span class="hljs-attr">"request"</span>: <span class="hljs-string">"launch"</span>,
            <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Launch Program"</span>,
            <span class="hljs-attr">"skipFiles"</span>: [
                <span class="hljs-string">"&lt;node_internals&gt;/**"</span>
            ],
            <span class="hljs-attr">"program"</span>: <span class="hljs-string">"${workspaceFolder}\\\\src\\\\index.ts"</span>,
            <span class="hljs-attr">"outFiles"</span>: [
                <span class="hljs-string">"${workspaceFolder}/**/*.js"</span>
            ]
        }
    ]
}
</code></pre>
<p>Replace it with the following configuration:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"version"</span>: <span class="hljs-string">"0.2.0"</span>,
    <span class="hljs-attr">"configurations"</span>: [
        {
            <span class="hljs-attr">"type"</span>: <span class="hljs-string">"node"</span>,
            <span class="hljs-attr">"request"</span>: <span class="hljs-string">"launch"</span>,
            <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Launch + auto-restart"</span>,
            <span class="hljs-attr">"runtimeExecutable"</span>: <span class="hljs-string">"${workspaceRoot}/node_modules/.bin/ts-node-dev"</span>,
            <span class="hljs-attr">"args"</span>: [
                <span class="hljs-string">"--respawn"</span>,
                <span class="hljs-string">"${workspaceRoot}/src/index.ts"</span> 
            ]
        }
    ]
}
</code></pre>
<p>The main properties to notice here are:</p>
<ul>
<li><p><code>runtimeExecutable</code>: By default, this would be <code>node</code>, but we are replacing it with <code>ts-node-dev</code></p>
</li>
<li><p><code>args</code>: We’re adding the <code>--respawn</code> flag, which tells <code>ts-node-dev</code> to restart the process when files change, and then we add the path to our startup file.</p>
</li>
</ul>
<p>Essentially, these two properties produce a result similar to the <code>ts-node-dev --respawn src/index.ts</code> script we set up earlier in the <code>package.json</code>.</p>
<h2 id="heading-now-lets-try-it">Now, let’s try it!</h2>
<p>Press <code>F5</code> to start the debugger. You should see the output on VSCode’s integrated terminal:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681610612870/524ebbb0-6397-472a-bbcc-8c9cee69f112.png" alt class="image--center mx-auto" /></p>
<p>Try adding a breakpoint, and then make some changes and save:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681610661284/d92d0133-4214-48a8-bc59-b830e623f084.png" alt class="image--center mx-auto" /></p>
<p>The app should restart and hit the breakpoint!</p>
<h2 id="heading-thats-it">That's it!</h2>
<p>What I love about this config is how simple it is. All we needed was <code>ts-node-dev</code>, a few tweaks to the debugger config file, and it just works!</p>
<p>Although, to be completely honest, I'll probably still use <code>console.log('here')</code> every now and then, just for old times' sake.</p>
<hr />
<p><a target="_blank" href="https://www.typescriptgamified.com"><img src="https://www.typescriptgamified.com/_app/immutable/assets/banner-01-16795b9b.webp" alt /></a></p>
<p>My book: <a target="_blank" href="https://typescriptgamified.com">typescriptgamified.com</a> | Find me here: <a target="_blank" href="https://paulasantamaria.com/links">paulasantamaria.com/links</a></p>
]]></content:encoded></item><item><title><![CDATA[MongoDB Animated: Adding and removing elements from arrays]]></title><description><![CDATA[Last week I had to work on an old project with MongoDB. A few documents with embedded arrays needed to be updated, and I realized that every time I have to…]]></description><link>https://blog.paulasantamaria.com/mongodb-animated-adding-and-removing-elements-from-arrays</link><guid isPermaLink="true">https://blog.paulasantamaria.com/mongodb-animated-adding-and-removing-elements-from-arrays</guid><category><![CDATA[MongoDB]]></category><category><![CDATA[mongoose]]></category><category><![CDATA[Databases]]></category><dc:creator><![CDATA[Paula Santamaría]]></dc:creator><pubDate>Fri, 29 Jan 2021 17:54:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1611943326577/aRozh6rvW.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Last week I had to work on an old project with MongoDB. A few documents with <em><strong>embedded arrays</strong></em> needed to be updated, and I realized that every time I have to do this sort of operations, I end up googling a lot to re-learn things I forgot.</p>
<p>So this time I decided to take thorough notes of everything I learn and write an article with examples so future Paula can go directly to the examples instead of googling everything all over again. And hey! Maybe someone else finds it useful as well.</p>
<p>I also included short animations illustrating each example 🤓</p>
<ul>
<li><a class="post-section-overview" href="#introduction">Introduction</a></li>
<li><a class="post-section-overview" href="#adding-new-elements-into-the-array">Adding new elements into the array</a><ul>
<li><a class="post-section-overview" href="#adding-a-single-element-at-the-end">Adding a single element at the end</a></li>
<li><a class="post-section-overview" href="#adding-a-single-element-into-a-specific-position">Adding a single element into a specific position</a></li>
<li><a class="post-section-overview" href="#adding-multiple-elements">Adding multiple elements</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#removing-an-element-from-the-array">Removing an element from the array</a></li>
<li><a class="post-section-overview" href="#try-it-yourself">Try it yourself</a></li>
<li><a class="post-section-overview" href="#resources">Resources</a></li>
</ul>
<h1 id="introduction">Introduction</h1>
<p>In this article I'm only going to talk about <strong>adding</strong> and <strong>removing</strong> elements from documents with embedded arrays. I will be posting a new article next week about how to update the contents of elements in the array.</p>
<p>The example DB we are going to use consists of a simple <em>collection</em> of "donut combos" from a donut shop. Each combo has a <em>name</em> and an <em>array of donuts</em> that will be included if the customer chooses that combo. Here's the complete schema:</p>
<pre><code class="lang-js"><span class="hljs-comment">// donutCombo Schema</span>
{
    <span class="hljs-attr">name</span>: { <span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>, <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span> },
    <span class="hljs-attr">active</span>: { <span class="hljs-attr">type</span>: <span class="hljs-built_in">Boolean</span>, <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span> },
    <span class="hljs-attr">donuts</span>: [{
        <span class="hljs-attr">color</span>: { <span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span> },
        <span class="hljs-attr">glazing</span>: { <span class="hljs-attr">type</span>: <span class="hljs-built_in">Boolean</span> }
    }]
}
</code></pre>
<h1 id="adding-new-elements-into-the-array">Adding new elements into the array</h1>
<p>We can add a new element to an array using the <code>$push</code> operator. By default, the new element will be added at the end of the array.</p>
<h3 id="adding-a-single-element-at-the-end">Adding a single element at the end</h3>
<p>In the following example, we will add a pink donut to the first document found with <code>name</code> "No Choco".</p>
<pre><code class="lang-js">db.donutCombos.updateOne({ <span class="hljs-attr">name</span>: <span class="hljs-string">"No Choco"</span> }, {
    <span class="hljs-attr">$push</span>: {
        <span class="hljs-attr">donuts</span>: {
            <span class="hljs-attr">color</span>: <span class="hljs-string">"pink"</span>,
            <span class="hljs-attr">glazing</span>: <span class="hljs-literal">true</span>
        }
    }
});
</code></pre>
<p><img src="https://i.imgur.com/WiskZLy.gif" alt="MongoDB finds the document where the name is &quot;No Choco&quot; and adds a pink donut at the end of the donuts array" /></p>
<h3 id="adding-a-single-element-into-a-specific-position">Adding a single element into a specific position</h3>
<p>Using the <code>$position</code> modifier, we can specify where in the array we want our new elements to be positioned. In order to use the <code>$position</code> modifier, we also need to use the <code>$each</code> modifier, even though we are only adding a single element.</p>
<p>In the following example, we will add a pink donut to the first document found with <code>name</code> "No Choco", in the <em>2nd position </em>of the array.</p>
<pre><code class="lang-js">db.donutCombos.updateOne({ <span class="hljs-attr">name</span>: <span class="hljs-string">"No Choco"</span> }, {
    <span class="hljs-attr">$push</span>: {
        <span class="hljs-attr">donuts</span>: {
            <span class="hljs-attr">$position</span>: <span class="hljs-number">2</span>,
            <span class="hljs-attr">$each</span>: [{
                <span class="hljs-attr">color</span>: <span class="hljs-string">"pink"</span>,
                <span class="hljs-attr">glazing</span>: <span class="hljs-literal">true</span>
            }]
        }
    }
});
</code></pre>
<p><img src="https://i.imgur.com/rir1Aaq.gif" alt="MongoDB finds the document where the name is &quot;No Choco&quot; and adds a pink donut at position 2 of the array" /></p>
<h3 id="adding-multiple-elements">Adding multiple elements</h3>
<p>Using the modifier <code>$each</code> we can push more than one element into our array.</p>
<p>In the following example, we will add two donuts (white and chocolate) at the end of the array in the first document with name "B&amp;W".</p>
<pre><code class="lang-js">db.donutCombos.updateOne({ <span class="hljs-attr">name</span>: <span class="hljs-string">"B&amp;W"</span> }, {
    <span class="hljs-attr">$push</span>: {
        <span class="hljs-attr">donuts</span>: {
            <span class="hljs-attr">$each</span>: [
                { <span class="hljs-attr">color</span>: <span class="hljs-string">"white"</span>, <span class="hljs-attr">glazing</span>: <span class="hljs-literal">true</span> },
                { <span class="hljs-attr">color</span>: <span class="hljs-string">"chocolate"</span>, <span class="hljs-attr">glazing</span>: <span class="hljs-literal">true</span> }
            ]
        }
    }
});
</code></pre>
<p><img src="https://i.imgur.com/WsjeU4e.gif" alt="MongoDB finds the document where the name is &quot;B&amp;W&quot; and adds a white donut and a chocolate donut at the end of the array" /></p>
<h1 id="removing-an-element-from-the-array">Removing an element from the array</h1>
<p>To remove an element from the array we use the operator <code>$pull</code>. Inside the $pull object we must specify a key-value pair: the key is the name of the array property from our document and the value is the filter we want to apply to define which elements should be removed.</p>
<p>In the following example, we will remove all the <em>white</em> donuts from the <em>active</em> documents in the <em>donutCombos</em> collection.</p>
<pre><code class="lang-js">db.donutCombos.updateMany({ <span class="hljs-attr">active</span>: <span class="hljs-literal">true</span> }, {
    <span class="hljs-attr">$pull</span>: {
        <span class="hljs-attr">donuts</span>: { <span class="hljs-attr">color</span>: <span class="hljs-string">"white"</span> }
    }
});
</code></pre>
<p><img src="https://i.imgur.com/QkLvWUG.gif" alt="MongoDB finds all active documents removes all the white donuts" /></p>
<h1 id="try-it-yourself">Try it yourself</h1>
<p>I created a repo to try MongoDB queries in memory using Node.js with Jest and MongoDB Node driver. I use tests to execute the query and verify if everything was correctly updated. I also included a logger that prints the updated documents in the console displaying the changes that were applied using diff highlight syntax:</p>
<p><img src="https://i.imgur.com/8yGmVkY.png" alt="The difference of a MongoDB document after being updated" /></p>
<p>You can find the examples I included in this article in the <code>tests</code> folder:</p>
<p>{% github pawap90/try-mongodb-queries %}</p>
<h1 id="resources">Resources</h1>
<p>For more info about updating arrays here are a few resources from MongoDB's official docs:</p>
<ul>
<li><p><a target="_blank" href="https://docs.mongodb.com/manual/reference/operator/update-array/">Array Update Operators (docs.mongodb.com)</a></p>
</li>
<li><p><a target="_blank" href="https://docs.mongodb.com/drivers/node/fundamentals/crud/write-operations/embedded-arrays">Update Arrays in a Document (docs.mongodb.com)</a></p>
</li>
</ul>
]]></content:encoded></item></channel></rss>