PROGRAMING/FULL STACK

[MongoDB] Reuse connection

donghunl 2024. 3. 20. 07:38
반응형

Endpoint마다 일일히 연결했던 MongoDB Connection을 재사용 가능하게 변경하도록 합니다.

그러기 위해 db.js파일을 src폴더 안에 생성해줍니다. 그안에 MongoDB에 연결을 하는 함수를 정의 해줍니다.

db.js

import { MongoClient } from 'mongodb';

let db;

async function connectToDb(cb) {
    const client = new MongoClient('mongodb://127.0.0.1:27017');
    await client.connect();
    db = client.db('react-blog-db');
    cb();
}

export {
    db,
    connectToDb,
};

 

다음은 이 함수를 불러들이는 server.js를 수정해 줍니다.

server.js

import express from 'express';
import { db, connectToDb } from './db.js';

const app = express();
app.use(express.json());

app.get('/api/articles/:name', async (req, res) => {
    const { name } = req.params;

    const article = await db.collection('articles').findOne({ name });

    if (article) {
        res.json(article);
    } else {
        res.sendStatus(404);
    }
});

app.put('/api/articles/:name/upvote', async (req, res) => {
    const { name } = req.params;

    await db.collection('articles').updateOne({ name }, {
        $inc: { upvotes: 1 },
    });
    const article = await db.collection('articles').findOne({ name });

    if (article) {
        res.send(`The ${name} article now has ${article.upvotes} upvotes!!!`);
    } else {
        res.send('That article doesn\'t exist');
    }
});

app.post('/api/articles/:name/comments', async (req, res) => {
    const { name } = req.params;
    const { postedBy, text } = req.body;

    await db.collection('articles').updateOne({ name }, {
        $push: { comments: { postedBy, text } },
    });
    const article = await db.collection('articles').findOne({ name });

    if (article) {
        res.send(article.comments);
    } else {
        res.send('That article doesn\'t exist!');
    }
});

connectToDb(() => {
    console.log('Successfully connected to database!');
    app.listen(8000, () => {
        console.log('Server is listening on port 8000');
    });
})

 

반응형

'PROGRAMING > FULL STACK' 카테고리의 다른 글

[Front End - Back End] Adding React hooks  (0) 2024.03.21
[Front End - Back End] The Axios library  (0) 2024.03.21
[MongoDB] Rewriting comments  (0) 2024.03.20
[MongoDB] Rewriting upvote  (0) 2024.03.20
[MongoDB] Adding MongoDB to Express  (0) 2024.03.20