PROGRAMING/FULL STACK

[MongoDB] Rewriting comments

donghunl 2024. 3. 20. 06:06
반응형

블로그의 댓글을 이제 MongoDB에 저장하여 연결 하도록 하겠습니다.

이전에 사용했던 Post method를 수정해서 구현하였고 변경된 코드는 다음과 같습니다.

server.js

import express from 'express';
import { MongoClient } from 'mongodb';

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

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

    const client = new MongoClient('mongodb://127.0.0.1:27017');
    await client.connect();

    const db = client.db('react-blog-db');

    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;

    const client = new MongoClient('mongodb://127.0.0.1:27017');
    await client.connect();

    const db = client.db('react-blog-db');
    await db.collection('articles').updateOne({ name }, {
        $inc: { upvotes: 1 }, // inclement upvote by 1
    });
    const article = await db.collection('articles').findOne({ name });

    if (article) {
        article.upvotes += 1;
        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;

    const client = new MongoClient('mongodb://127.0.0.1:27017');
    await client.connect();

    const db = client.db('react-blog-db');
    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!');
    }
});

app.listen(8000, () => {
    console.log('Server is listening on port 8000');
});

 

결과 화면은 다음과 같습니다.

댓글 또한 MongoDB에 저장되어져서 서버를 다시 시작해도 리셋되지 않습니다.

반응형

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

[Front End - Back End] The Axios library  (0) 2024.03.21
[MongoDB] Reuse connection  (0) 2024.03.20
[MongoDB] Rewriting upvote  (0) 2024.03.20
[MongoDB] Adding MongoDB to Express  (0) 2024.03.20
[MongoDB] MongoDB 실행  (0) 2024.03.19