mongodb 준비하기
늘 그렇듯 이번 데이터베이스도 docker로 준비한다.

이렇게 준비를 해두고, 실행한다.
mongodb 연결하기
우선 다음과 같이 라이브러리들을 설치한다.
npm install morgan nunjucks mongoose
이 mongoose가 node에 굉장히 잘맞는거로 기억이 난다.
import mongoose from 'mongoose';
export async function connect() {
if (process.env.NODE_ENV !== 'production') {
mongoose.set('debug', true);
}
try {
await mongoose.connect(
'mongodb://seungkyu:1204@localhost:27017/express?authSource=admin',
);
console.log('MongoDB Connected');
} catch (err) {
console.error(err);
}
mongoose.connection.on('error', (err) => console.log(err));
}
그리고 위와 같이 데이터베이스 연결을 생성하는 함수를 만들고
import express from 'express';
import dotenv from 'dotenv';
import { connect } from './schemas/index.js';
dotenv.config();
const app = express();
app.set('port', process.env.PORT || 3000);
async function start() {
try {
await connect();
app.listen(app.get('port'), () => {
console.log(`Server on port ${app.get('port')}`);
});
} catch (error) {
console.error('MongoDB 연결 실패:', error);
process.exit(1);
}
}
start();
이렇게 app.ts를 수정해준다.
그리고 실행해보면 아래와 같이 연결이 잘 생성되는 것을 볼 수 있다.

Schema 정의하기
이제 데이터를 저장하기 위한 판인 Schema를 정의해보자.
모든 테이블에 id를 습관적으로 만들었는데, mongodb는 알아서 _id로 만들어주기에 생성할 필요가 없다고 한다.
schema는 다음과 같이 작성한다.
import mongoose, { Schema } from 'mongoose';
export interface IUser {
name: string;
age: number;
email: string;
password: string;
createdAt: Date;
updatedAt: Date;
}
const userSchema = new Schema<IUser>(
{
name: {
type: String,
required: true,
trim: true,
},
age: {
type: Number,
required: true,
min: 0,
},
email: {
type: String,
required: true,
unique: true,
lowercase: true,
trim: true,
},
password: {
type: String,
required: true,
},
},
{
timestamps: true, // createdAt, updatedAt 자동 생성
},
);
export default mongoose.model<IUser>('User', userSchema);
import mongoose, { Schema } from 'mongoose';
export interface ILecture {
name: string;
code: string;
user: mongoose.Types.ObjectId;
}
const lectureSchema = new Schema<ILecture>(
{
name: {
type: String,
required: true,
},
code: {
type: String,
required: true,
unique: true,
},
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true,
},
},
{
timestamps: true,
},
);
export default mongoose.model<ILecture>('Lecture', lectureSchema);
쿼리 작성하기
쿼리는 작성한 스키마를 가져와서 다음과 같이 함수를 호출하는 것으로 사용한다.
import express, { Request } from 'express';
import User from '../schemas/user.js';
const router = express.Router();
interface CreateUserRequest {
name: string;
age: number;
email: string;
password: string;
}
interface UpdateUserRequest {
id: string;
name: string;
age: number;
email: string;
password: string;
}
router.get('/', async (_req, res) => {
const users = await User.find({});
res.json(users);
});
router.get('/:id', async (req, res) => {
try {
const user = await User.findById(req.params.id);
if (!user) {
return res.status(404).json({
message: 'User not found',
});
}
return res.json(user);
} catch (_err: any) {
return res.status(400).json({
message: 'Invalid ObjectId',
});
}
});
router.post(
'/',
async (req: Request<object, object, CreateUserRequest>, res) => {
const user = await User.create({
name: req.body.name,
age: req.body.age,
email: req.body.email,
password: req.body.password,
});
return res.status(201).json(user);
},
);
router.patch(
'/:id',
async (req: Request<object, object, UpdateUserRequest>, res) => {
const id = req.body.id;
const user = await User.updateMany(
{
_id: id,
},
{
name: req.body.name,
age: req.body.age,
email: req.body.email,
password: req.body.password,
},
);
return res.status(20).json(user);
},
);
router.delete('/:id', async (req, res) => {
const result = await User.deleteOne({ _id: req.params.id });
res.json(result);
});
export default router;
우선 POST부터 테스트를 해보면
POST http://localhost:3000/users
Content-Type: application/json
{
"name": "김승규",
"age": 25,
"email": "test@test.com",
"password": "1234"
}

이렇게 잘 생성이 된 것을 볼 수 있다.
이제 GET을 테스트 해보자.
전체 조회는
GET http://localhost:3000/users
Content-Type: application/json

id를 사용한 조회는
GET http://localhost:3000/users/6a3fc8b574989b798e660fa2
Content-Type: application/json

이렇게 잘 조회가 되며
PATCH, DELETE를 테스트해보면
PATCH http://localhost:3000/users/6a3fc8b574989b798e660fa2
Content-Type: application/json
{
"name": "한승규",
"age": 25,
"email": "test@test.com",
"password": "1234"
}

DELETE http://localhost:3000/users/6a3fc8b574989b798e660fa2
Content-Type: application/json

이렇게 삭제가 성공적으로 되는 것을 볼 수 있다.
'Node > Node.js' 카테고리의 다른 글
| express로 pg 사용하기 (0) | 2026.06.27 |
|---|---|
| express 시작하기 (0) | 2026.06.27 |
| 노드 패키지 매니저 (0) | 2026.06.24 |
| 노드로 http 서버 만들어보기 (0) | 2026.06.23 |
| 노드 사용해보기 (0) | 2026.06.22 |



































