[TIL] Converting MySQL -> MongoDB (NoSQL)
05/18/23
![[TIL] Converting MySQL -> MongoDB (NoSQL)](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1688363556918%2F8788d0ba-3ae5-428e-a039-64b6b673ea05.png&w=3840&q=75)
๐ Issues encountered
Issue #1
When querying the entire chat history from MySQL, the query took too long. When testing with Postman, it took around 2.xx seconds.
Issue #2
Adding MongoDB connection.
๐ What I tried
Issue #1
There were two tables to join with the Chats table in MySQL, and the part where the entire chat history was queried required a lot of query executions and processing to manipulate the returned objects in the service layer.
Therefore, I decided to change the Chats table in MySQL to MongoDB, and created two schemas: Chats schema and Messages schema.
Chat-related data is stored in MongoDB, while the rest is stored in MySQL, so I added MySQL data to the Chats schema to minimize the parts that fetch data from MySQL while performing CRUD operations on Chat.
The Chats schema includes fields such as title, is_sold, product_id, members, members_nickname, and address.
After actually changing the Chat part to MongoDB, the query time decreased from 2.xx seconds to around 600 ms.
Issue #2
- In
utils/mongodb.js, I defined the part that connects to MongoDB as follows:
const mongoose = require("mongoose");
const { mongodb } = require("../config/config.js");
const db_url = `mongodb+srv://${mongodb.id}:${mongodb.password}@${mongodb.cluster}/${mongodb.db}?retryWrites=true&w=majority`;
const connectToMongoDB = async (app) => {
mongoose
.connect(db_url)
.then(() => {
console.log("MongoDB connected")
})
.catch((err) => {
throw err;
});
};
module.exports = connectToMongoDB;
- In
app.js, I imported MongoDB as follows:
const connectToMongoDB = require("./utils/mongodb");
connectToMongoDB(app);
- In the
schemafolder, I defined the Chats and Messages schemas and imported them in the respective repositories where these schemas are used.
![[์ฝํ
] ๊ทธ๋ฆฌ๋ ๋ฌธ์ - ๋ฌด์ง์ ๋จน๋ฐฉ ๋ผ์ด๋ธ](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1712215455263%2F1ac1f35a-8862-4e42-8d0c-e2bea01e04c0.png&w=3840&q=75)
![[์ฝํ
] Bfs ํ ๋งํ](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1709032619170%2F70056896-c857-444b-9c99-45bfcb466806.png&w=3840&q=75)
![[์ฝํ
] Dfs ๋ฌธ์ ์ ํ - ๊ทธ๋ํ ๋ด์์ ๊ตฌ๋ถํ์ฌ ์นด์ดํธ ํ๊ธฐ](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1709019361383%2Fb0585d72-c808-4169-83a9-2724f312e927.png&w=3840&q=75)
![[์ฝํ
] DFS vs BFS](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1708971211123%2F71f9386c-6a62-43b2-a602-4d084c24d6cf.png&w=3840&q=75)
![[์ฝํ
] ์ฌํ๊ฒฝ๋ก](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1708971251412%2F27ce72ed-8ee7-4d13-a02f-ff4bbe50c4be.png&w=3840&q=75)