<?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 O Muhammetcorduk on Medium]]></title>
        <description><![CDATA[Stories by O Muhammetcorduk on Medium]]></description>
        <link>https://medium.com/@o.muhammetcorduk?source=rss-a63476c6e104------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*tbuAbQPR2O-Vduht</url>
            <title>Stories by O Muhammetcorduk on Medium</title>
            <link>https://medium.com/@o.muhammetcorduk?source=rss-a63476c6e104------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 12:12:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@o.muhammetcorduk/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[Migrating Your Database from MongoDB to MySQL: A Comprehensive Guide]]></title>
            <link>https://medium.com/@o.muhammetcorduk/migrating-your-database-from-mongodb-to-mysql-a-comprehensive-guide-9faa98f1910c?source=rss-a63476c6e104------2</link>
            <guid isPermaLink="false">https://medium.com/p/9faa98f1910c</guid>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[O Muhammetcorduk]]></dc:creator>
            <pubDate>Wed, 13 Mar 2024 19:10:26 GMT</pubDate>
            <atom:updated>2024-03-13T19:10:26.506Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*skJCtRTU6im9vnuLwsnx2A.png" /></figure><p>In the world of software development, data is king. The way we store, retrieve, and manage this data can significantly impact the performance and scalability of our applications. What happens when you need to migrate your data from MongoDB to MySQL? This article will guide you through the process, but first, let’s understand what these two database systems are.</p><h4>MongoDB: The Document-Oriented Database</h4><p>MongoDB is a No-SQL database, which means it does not rely on the traditional table-based relational database structure. Instead, it opts for a more flexible, document-oriented model. In MongoDB, data is stored in BSON documents — binary JSON format, which allows for a more diverse data representation. This flexibility makes MongoDB an excellent choice for projects that require the ability to store large volumes of non-uniform data, hence why you might bump into MongoDB in small or personal projects, but it also means that data integrity is not enforced as strictly as in relational databases.</p><h4>MySQL: The Relational Database</h4><p>On the other hand, MySQL is a relational database management system (RDBMS). It stores data in tables and uses structured query language (SQL) for database access. In MySQL, data is stored in rows and columns, and each table’s structure is fixed with a predefined schema. This structure allows for data integrity and complex queries, making MySQL a great choice for applications that require multi-row transactions — like accounting systems or systems that monitor inventory — or for applications that require a high degree of data integrity. SQL databases are also the ones commonly preferred by Enterprises.</p><h3>Understanding the Database Structure</h3><p>Before we dive into the migration process, let’s understand the structure of our MongoDB database. We have an e-commerce database with two collections: Users and Orders.</p><p>The Users collection stores user information, including a unique identifier (userId), the user&#39;s name, email, password, and address. The address field is an embedded document that contains the user&#39;s street, city, state, and zip code.</p><pre>{<br>    &quot;userId&quot;: &quot;user1&quot;,<br>    &quot;name&quot;: &quot;Muhammet Corduk&quot;,<br>    &quot;email&quot;: &quot;muhammet.corduk@example.com&quot;,<br>    &quot;password&quot;: &quot;hashed_password&quot;,<br>    &quot;address&quot;: {<br>        &quot;street&quot;: &quot;123 Main St&quot;,<br>        &quot;city&quot;: &quot;Anytown&quot;,<br>        &quot;state&quot;: &quot;Anystate&quot;,<br>        &quot;zip&quot;: &quot;12345&quot;<br>    }<br>}</pre><p>The Orders collection stores order information. Each order includes a unique identifier (orderId), the userId of the user who placed the order, the date the order was placed, the total cost of the order, and an array of items. Each item is an embedded document that contains a product identifier, the product&#39;s name, the quantity ordered, and the price per unit.</p><pre>{<br>    &quot;orderId&quot;: &quot;order1&quot;,<br>    &quot;userId&quot;: &quot;user1&quot;,<br>    &quot;date&quot;: &quot;2022-01-01&quot;,<br>    &quot;total&quot;: 100.00,<br>    &quot;items&quot;: [<br>        {<br>            &quot;productId&quot;: &quot;product1&quot;,<br>            &quot;name&quot;: &quot;Product 1&quot;,<br>            &quot;quantity&quot;: 2,<br>            &quot;price&quot;: 25.00<br>        },<br>        {<br>            &quot;productId&quot;: &quot;product2&quot;,<br>            &quot;name&quot;: &quot;Product 2&quot;,<br>            &quot;quantity&quot;: 1,<br>            &quot;price&quot;: 50.00<br>        }<br>    ]<br>}</pre><p>This database structure covers different types of data (strings, numbers, dates, arrays, and embedded documents) and includes a relationship between collections (userId in Orders references userId in Users).</p><h3>Design the MySQL Schema</h3><p>In MongoDB, the data is pretty straight-forward as most of us are familiar with JSON. MongoDB’s document-oriented nature allows for flexible and hierarchical data structures. Remind yourself that in MySQL, data is stored in rows and columns. These rows and columns make up tables, and each table’s structure is fixed with a predefined schema.</p><p>First, we need to design a MySQL schema that can accommodate the MongoDB data. Our MongoDB Database has two collections, for transition to SQL, we will need at least two tables for our Users and Orders . Let’s take a look at Userfirst:</p><ul><li>userId (INT PRIMARY KEY) — Unique identifier for the user (int)</li><li>name (VARCHAR(255)) — User’s name (string)</li><li>email (VARCHAR(255) UNIQUE) — User’s email (string, unique)</li><li>password (VARCHAR(255)) — User’s password (encrypted string)</li><li>street (VARCHAR(255)) — User’s street address (string)</li><li>city (VARCHAR(255)) — User’s city (string)</li><li>state (VARCHAR(255)) — User’s state (string)</li><li>zip (VARCHAR(255)) — User’s zip code (string)</li></ul><p>The column data up above is structured in the following way:</p><ul><li><strong>Field Name:</strong> This is the name you assign to the column in the table.</li><li><strong>Data Type:</strong> This specifies the kind of data the field can hold (e.g., INT, VARCHAR, DATE, DECIMAL).</li><li><strong>Size (Optional):</strong> For certain data types like VARCHAR, you can define the maximum length of the data the field can store (e.g., VARCHAR(255) allows strings up to 255 characters).</li></ul><p>Primary Key is like _id from MongoDB, basically a unique identifier. MySQL won’t give you some auto created id like MongoDB does but you can use your own unique data instead.</p><p>You may have noticed that our adress object from our mongoDB document is flattened, the reason for this is MySQL won’t support nested data structures, therefore we flatten adress. We could also seperate adress to it’s own table but to keep things simpler we avoid it for now.</p><p>Secondly our Orders table:</p><ul><li>orderId (INT PRIMARY KEY) — Unique identifier for the order (int)</li><li>userId (INT FOREIGN KEY REFERENCES Users(userId)) — Identifier of the user who placed the order (int, foreign key referencing Users.userId)</li><li>date (DATE) — Date when the order was placed (date)</li><li>total (DECIMAL(10,2)) — Total cost of the order (decimal)</li></ul><p>Foreign keys create links between related tables in relational databases, similar to we include userId in orders collection documents, we include userId in our Orders table.</p><p>Lastly, as explained before we can’t have nested data in MySQL. Since it won’t support our array of objects we can instead have a seperate table, let’s call it OrderItems , where each object in items will be a row in this new table. OrderItems table:</p><ul><li>orderId: The identifier of the order.</li><li>productId: The identifier of the product.</li><li>name: The product&#39;s name.</li><li>quantity: The quantity ordered.</li><li>price: The price per unit.</li></ul><p>While it might seem inefficient to have a separate table for order items, it’s actually a very efficient way to model this kind of relationship in a relational database like MySQL. You can have very flexible queries due to the way our MySQL schemas are defined.</p><p>Here is relationship of our tables:</p><pre>(1)        (N)<br>Users ---- userId -----&gt; Orders<br>                        |<br>                        v<br>(1)        (N)<br>Orders ---- orderId -----&gt; OrderItems<br>                        |<br>                        v<br>                        (Many to Many)<br>                        Products (May be added in the future)</pre><ul><li>A user can have many orders, but each order is associated with one user.</li><li>An order can have many items, but each order item is associated with one order.</li></ul><h3>Migrate to MySQL</h3><h4>Export MongoDB Data</h4><p>Now that we have our MySQL schema ready, the next step in our migration process is to export our data from MongoDB. MongoDB provides a utility called mongoexport that can be used to export data from a MongoDB database to a JSON or CSV file.</p><pre>mongoexport --db=ecommerce --collection=Users --out=Users.json<br>mongoexport --db=ecommerce --collection=Orders --out=Orders.json</pre><p>These commands assume you are connecting to the MongoDB server on the local host (localhost) with default port (27017). If your MongoDB server is on a different machine or uses a different port, you’ll need to specify those details using the --host and --port options in the commands. These commands will create Users.json and Orders.json files with the data from the respective collections.</p><h4>Transform the Data</h4><p>After exporting the data, the next step is to transform it to match our MySQL schema. The exported data is in JSON format, which is not directly compatible with MySQL. We need to flatten the nested address objects in the Users data and the items arrays in the Orders data. I preferred to write a script in Nodejs for this job that will transform our data for us:</p><pre>const fs = require(&#39;fs&#39;);<br>const csvWriter = require(&#39;csv-write-stream&#39;);<br><br>// Transform Users data<br>const users = JSON.parse(fs.readFileSync(&#39;Users.json&#39;, &#39;utf8&#39;));<br>const userWriter = csvWriter();<br>userWriter.pipe(fs.createWriteStream(&#39;Users.csv&#39;));<br>users.forEach(user =&gt; {<br>    userWriter.write({<br>        userId: user.userId,<br>        name: user.name,<br>        email: user.email,<br>        password: user.password,<br>        street: user.address.street,<br>        city: user.address.city,<br>        state: user.address.state,<br>        zip: user.address.zip<br>    });<br>});<br>userWriter.end();<br><br>// Transform Orders data<br>const orders = JSON.parse(fs.readFileSync(&#39;Orders.json&#39;, &#39;utf8&#39;));<br>const orderWriter = csvWriter();<br>orderWriter.pipe(fs.createWriteStream(&#39;Orders.csv&#39;));<br>const orderItemWriter = csvWriter();<br>orderItemWriter.pipe(fs.createWriteStream(&#39;OrderItems.csv&#39;));<br>orders.forEach(order =&gt; {<br>    orderWriter.write({<br>        orderId: order.orderId,<br>        userId: order.userId,<br>        date: order.date,<br>        total: order.total<br>    });<br>    order.items.forEach(item =&gt; {<br>        orderItemWriter.write({<br>            orderId: order.orderId,<br>            productId: item.productId,<br>            name: item.name,<br>            quantity: item.quantity,<br>            price: item.price<br>        });<br>    });<br>});<br>orderWriter.end();<br>orderItemWriter.end();</pre><p>Script provided will create three CSV files: Users.csv, Orders.csv, and OrderItems.csv. Each of these CSV files corresponds to a table in our MySQL database.</p><h4>Import Data into MySQL</h4><p>Once we have our data in CSV format, we can import it into MySQL. MySQL provides a command called LOAD DATA INFILE that can be used to import data from a CSV file into a table. Pretty cool, no?</p><p>Here’s how you can use LOAD DATA INFILE to import the Users, Orders, and OrderItems data:</p><pre>LOAD DATA INFILE &#39;/path/to/Users.csv&#39; <br>INTO TABLE Users <br>FIELDS TERMINATED BY &#39;,&#39; <br>ENCLOSED BY &#39;&quot;&#39;<br>LINES TERMINATED BY &#39;\n&#39;<br>IGNORE 1 ROWS;<br><br>LOAD DATA INFILE &#39;/path/to/Orders.csv&#39; <br>INTO TABLE Orders <br>FIELDS TERMINATED BY &#39;,&#39; <br>ENCLOSED BY &#39;&quot;&#39;<br>LINES TERMINATED BY &#39;\n&#39;<br>IGNORE 1 ROWS;<br><br>LOAD DATA INFILE &#39;/path/to/OrderItems.csv&#39; <br>INTO TABLE OrderItems <br>FIELDS TERMINATED BY &#39;,&#39; <br>ENCLOSED BY &#39;&quot;&#39;<br>LINES TERMINATED BY &#39;\n&#39;<br>IGNORE 1 ROWS;</pre><p>Change your paths and run this SQL query in our MySQL database. To get more detailed information about importing CSV to MySQL you can <a href="https://www.educative.io/answers/how-to-import-csv-into-mysql">read up about it</a> here.</p><h3>Conclusion</h3><p>This guide has walked you through the basic steps of the process, please keep in mind there are a few different ways to migrate databases such as:</p><ol><li><strong>ETL Tools</strong>: Extract, Transform, Load (ETL) tools are designed to handle data migrations like this. They can connect to your MongoDB and MySQL databases, transform the data as needed, and handle the import/export process automatically.</li><li><strong>Database Migration Services</strong>: Some cloud providers offer database migration services that can handle the transformation process. For example, AWS Database Migration Service supports migrating from MongoDB to Amazon Aurora (a MySQL-compatible database).</li></ol><p>Remember that each migration is unique and may require additional steps depending on your specific data and requirements. Always test the migration process with a subset of your data before running it on the entire database, and don’t hesitate to seek help if you encounter any issues. Good luck with your migration!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9faa98f1910c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Notification Service with Observer Pattern in Node.js and TypeScript]]></title>
            <link>https://medium.com/@o.muhammetcorduk/building-a-notification-service-with-observer-pattern-in-node-js-and-typescript-9dfc27269755?source=rss-a63476c6e104------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dfc27269755</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[observer-pattern]]></category>
            <dc:creator><![CDATA[O Muhammetcorduk]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 15:06:27 GMT</pubDate>
            <atom:updated>2024-03-04T15:06:27.152Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will be building a simple notification service that demonstrates the Observer design pattern in a Node.js application using TypeScript.</p><p>This is a follow-along article, you can <a href="https://github.com/Mcorduk/observer-in-node">find the repo here.</a> We will use new branches for each implementation and feature.</p><h3>Introduction</h3><p>The Observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems, in “event-driven” software.</p><p>In our case, the notification service is the subject, and the users are the observers. When the notification service sends a notification, all registered users will receive the notification.</p><p>In traditional object-oriented programming, the Observer pattern requires interfaces, concrete classes, and a hierarchy. Let’s explore that first.</p><h3>Implementing the Observer Pattern Traditionally</h3><p>Here is the most basic implementation of our pattern.</p><pre>import { Observer } from &quot;../types/Observer&quot;;<br><br>export class User implements Observer {<br>  constructor(private name: string) {}<br><br>  update(message: string): void {<br>    console.log(`${this.name} received a notification: ${message}`);<br>  }<br>}</pre><p>The User class has an update method, which is called when the subject&#39;s state changes.</p><pre>import { Subject } from &quot;../types/Subject&quot;;<br>import { Observer } from &quot;../types/Observer&quot;;<br><br>export class NotificationService implements Subject {<br>  private observers: Observer[] = [];<br><br>  registerObserver(o: Observer): void {<br>    this.observers.push(o);<br>  }<br><br>  removeObserver(o: Observer): void {<br>    const index = this.observers.indexOf(o);<br>    if (index !== -1) {<br>      this.observers.splice(index, 1);<br>    }<br>  }<br><br>  notifyObservers(message: string): void {<br>    for (let observer of this.observers) {<br>      observer.update(message);<br>    }<br>  }<br>}</pre><p>The NotificationService has methods for registering and removing observers, and for notifying observers of state changes.</p><p>Finally, in the index.ts file, we created a NotificationService instance and several User instances. We registered the users with the notification service, and then sent a notification.</p><pre>[nodemon] starting `ts-node src/index.ts`<br>User 1 received a notification: This is a test notification!<br>User 2 received a notification: This is a test notification!<br>User 3 received a notification: This is a test notification!</pre><h3>Event Emitter</h3><p>While the traditional Observer pattern is powerful and flexible, Node.js provides a built-in module that makes implementing this pattern even simpler and more idiomatic: the EventEmitter class.</p><p>EventEmitter is part of the events module in Node.js. It allows you to create objects that emit named events, which cause listener functions to be called. This is essentially the Observer pattern, but with a simpler and more flexible interface.</p><p>In the next section, I’ll show you how to refactor our notification service to use EventEmitter instead of the traditional Observer pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*HAkju4pNQ_OZNfn9sHb-kg.png" /><figcaption>Sequence diagram of emitting events.</figcaption></figure><p>We don’t need the Observer and Subject interfaces and the NotificationService class anymore. Instead, we&#39;ll use the EventEmitter.</p><pre>import { EventEmitter } from &#39;events&#39;;<br><br>class User {<br>  constructor(private name: string, private eventEmitter: EventEmitter) {<br>    this.eventEmitter.on(&#39;notification&#39;, (message: string) =&gt; {<br>      console.log(`${this.name} received a notification: ${message}`);<br>    });<br>  }<br>}<br><br>const eventEmitter = new EventEmitter();<br><br>const user1 = new User(&#39;User 1&#39;, eventEmitter);<br>const user2 = new User(&#39;User 2&#39;, eventEmitter);<br>const user3 = new User(&#39;User 3&#39;, eventEmitter);<br><br>eventEmitter.emit(&#39;notification&#39;, &#39;This is a test notification!&#39;);</pre><p>Exact same result with notifications being sent to our observer Users before.</p><h3><strong>Adding Persistence and HTTP API</strong></h3><p>The next sensible step is to add persistence to our app so we can store and retrieve our users and notifications later.</p><blockquote>Note that observer pattern itself is about in-memory objects and their interactions. When you introduce a database into the mix, you’re dealing with persistence, which is a separate concern. We however will not be focusing on persistence in this article.</blockquote><p>We will lift the a MongoDB database with Docker Compose and interact with it using Mongoose.</p><p>Additionally, we can add API endpoints to our application. This will allow other applications to interact with our notification service. For example, we could add endpoints to create notifications, view past notifications, subscribe and unsubscribe users, etc. Users could also be added to our DB but we will not be doing that to avoid extra complexity at this stage.</p><p>Not including the boilerplate, here is our endpoints:</p><pre><br>app.post(&quot;/notify&quot;, async (req, res) =&gt; {<br>  const { message } = req.body;<br>  eventEmitter.emit(&quot;notification&quot;, message);<br><br>  // Save the notification to MongoDB<br>  const notification = new Notification({ message });<br>  await notification.save();<br><br>  res.send({ message: &quot;Notification sent!&quot; });<br>});<br><br>app.post(&quot;/subscribe&quot;, (req, res) =&gt; {<br>  const { name } = req.body;<br>  if (users[name]) {<br>    return res.status(400).send({ message: &quot;User already subscribed&quot; });<br>  }<br>  users[name] = new User(name, eventEmitter);<br>  res.send({ message: &quot;User subscribed successfully&quot; });<br>});<br><br>app.post(&quot;/unsubscribe&quot;, (req, res) =&gt; {<br>  const { name } = req.body;<br>  if (!users[name]) {<br>    return res.status(400).send({ message: &quot;User not found&quot; });<br>  }<br>  delete users[name];<br>  res.send({ message: &quot;User unsubscribed successfully&quot; });<br>});<br>const server = app.listen(3000, () =&gt; {<br>  console.log(&quot;Server is running on port 3000&quot;);<br>});</pre><p>I have added some basic tests and we can see that all our endpoints are working as expected in our persistence-and-api branch.</p><h3>Real-Time Communication with Socket.io</h3><p>Now that we have a working notification service with persistence and an HTTP API, let’s take it a step further by adding real-time communication. This will allow us to push notifications to clients as soon as they are available, without the clients having to poll the server for updates.</p><p>To do this, we’ll use Socket.IO, a library that enables real-time, bidirectional communication between web clients and servers.</p><pre>const httpServer = new Server(app);<br>const io = new IOServer(httpServer);<br><br>io.on(&quot;connection&quot;, (socket) =&gt; {<br>  console.log(&quot;a user connected&quot;);<br>});</pre><p>We’re creating a new HTTP server and a new instance of Socket.IO. The io.on(&quot;connection&quot;, callback) method sets up a listener for new connections. When a client connects to the server, the callback function is called with the socket object representing the client.</p><pre>app.post(&quot;/notify&quot;, async (req, res) =&gt; {<br>  const { message } = req.body;<br>  eventEmitter.emit(&quot;notification&quot;, message);<br><br>  // Emit the notification to all connected Socket.IO clients<br>  io.emit(&quot;notification&quot;, message);<br><br>  // Save the notification to MongoDB<br>  const notification = new Notification({ message });<br>  await notification.save();<br><br>  res.send({ message: &quot;Notification sent!&quot; });<br>});</pre><p>In the /notify endpoint, we&#39;re using io.emit(&quot;notification&quot;, message) to send the notification to all connected clients. This is done in addition to emitting the notification to all observers via the event emitter.</p><blockquote><a href="https://socket.io/docs/v4/client-installation/">Visit this link</a> to understand how client connects to our socket.</blockquote><p>This setup allows us to use the Observer pattern to notify in-memory user objects, and Socket.IO to notify connected clients, all in one go. This is a powerful combination that allows for both in-process and real-time out-of-process notifications.</p><p>In socket-server branch you can see the new socket-test test imitating a client socket connected our socket server and getting a notification each time /notify endpoint is hit.</p><h3>Wrapping Up</h3><p>In this article, we’ve built a simple notification service using the Observer pattern in Node.js and TypeScript. We’ve seen how to use the EventEmitter class for in-process communication, and how to extend this with Socket.IO for real-time, out-of-process communication.</p><p>However, there are many aspects we didn’t cover in this article. Such as error handling, which is crucial in a real-world application, adding more features, such as the ability to send notifications to specific users or groups of users, or the ability to schedule notifications for a future time.</p><p>As a homework exercise, try implementing some of these improvements yourself. This will give you a deeper understanding of the Observer pattern.</p><p>In conclusion, the Observer pattern is a powerful tool for creating flexible, decoupled code. It’s particularly useful in event-driven applications, where you need to notify multiple objects of state changes. Try to notice how this pattern could be used in very popular applications other than the one we worked on (spoiler: real-time messaging) and how you could implement those using this article. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dfc27269755" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>