Nodejs with MongoDB(3)

Kim Seoung Hun·2022년 10월 25일
0

Nodejs with MongoDB

목록 보기
3/3
post-thumbnail

이제 유저정보를 받아야 저장하고 불러오는것 까지 구현하고자 한다.

먼저 유저정보를 받아오기 위해서 몽구스의 내장 기능인 스키마를 이용하고자 한다.
정보를 받아와야 할때 예를 들어 username 등 중요한 정보는 타입과 필수 여부를 넣어주어서 해당 조건이 아닐시 오류 메세지를 뱉을 수 있도록 하는것이다.

유저스키마는 따로 models 라는 폴더에 분리해서 불러오고자 한다 먼저,

src > models > User.js

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
    username: { type: String, required: true},
    name: {
        first: { type: String, required: true},
        last: { type: String, required: true},
    },
    age: Number,
    email: String
}, { timestamps: true });

const User = mongoose.model('user', UserSchema);
module.exports = { User };

server.js와 마찬가지로 몽구스를 불어오고 UserSchema를 정의해준다.

필수여부등 다른 조건사항이 없으면 바로 {} 없이 타입만 지정해주어도 된다.

timestamps : true 는 유저가 만들어진 순간, 수정된 수간을 저장해준다.

다 만들고 나면 export 해주어서 server.js에서 이 스키마를 사용 할 수 있도록 해준다.

module.exports VS export default

server.js

const express = require("express");
const app = express();
const mongoose = require('mongoose');
const { User } = require('./models/User');

const MONGO_URI = "mongodb+srv://kimseounghun:<password>@mongodbstudy.rgulq2j.mongodb.net/BlogService?retryWrites=true&w=majority";

const server = async() => {
    try {
        await mongoose.connect(MONGO_URI);
        console.log('mongodb conneted!');
        app.use(express.json())

        app.get('/user', async (req, res) => {
            try {
                const users = await User.find({});
                return res.send({ users })
            } catch (error) {
                console.log(error);
            }
        });

        app.post('/user', async (req, res) => {
            try {
                let { username, name } = req.body;
                if(!username) {
                    return res.status(400).send({
                        error: "user name is required"
                    });
                };
                if(!name || !name.first || !name.last) {
                    return res.status(400).send({
                        error: "Both first and last names are required"
                    });
                };
                const user = new User(req.body); //몽구스롤 인스터스를 만듦
                await user.save(); //성공적으로 저장이 되면 
                return res.send({ user }) // User 리턴해줌
                // return res.send({success: true}) // 성공을 리턴해줌
            } catch (error) {
                console.log(error);
                return res.status(500).send({ error: error.message})
            }
        })

        app.listen(3000, () => {
            console.log('server listening on port 3000'); 
        })

    } catch (error) {
        console.log(error);
    }
}

server();

post 요청안에 조건문을 넣어 각 오류 상황에 대해서 오류코드를 설정해준다.
함수가 잘못된경우 오류코드 500을 클라이언트가 값을 전달할때 username, name 정도를 이상하게 주면 오류코드 400을 뱉어내도록 해준다.


get 요청시 User.find({}) 을 하게 되면 유저 데이터 전체를 불러오고, User.findOne({})을 하게 되면 객채를 불러온다.

위 코드는 유저정보 전체를 불러오는거여서 User.find({})를 사용한다.

근데, username같은 정보는 중복이 되면 안될거 같은 중요한 정보라고 생각이되어 중복되지 않도록 해주고 싶다.

이를 위해서 유저 스키마에 unique: true 를 넣어주면 끝.

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
    username: { type: String, required: true, unique: true},
    name: {
        first: { type: String, required: true},
        last: { type: String, required: true},
    },
    age: Number,
    email: String
}, { timestamps: true });

const User = mongoose.model('user', UserSchema);
module.exports = { User };

대신 기존에 쌓여있던 중복?유저네임 데이터를 다 지우고 서버를 재실행 해주자.

같은 정보를 포스트맨으로 post하면

profile
낮 코딩 밤에는 그림 종종 시

0개의 댓글