Mongoose#
Mongoose는 MongoDB와 Node.js 애플리케이션을 연결해주는 강력한 Object Document Mapper(ODM) 라이브러리이다.
데이터베이스와 애플리케이션 사이의 다리 역할을 하며, 데이터 모델링과 검증을 쉽게 만들어준다.
Mongoose의 장점#
- 강력한 스키마 정의
- 데이터 검증
- 중첩된 데이터 모델링
- 쉬운 쿼리 작성
- 미들웨어 지원
주의사항#
- 성능에 민감한 대규모 애플리케이션에서는 쿼리 최적화 필요
- 복잡한 관계와 조인은 추가 설계 필요
- 과도한 스키마 복잡성 피하기
Mongoose의 주요 개념#
스키마 (Schema)#
데이터의 구조를 정의하는 청사진.
각 필드의 타입, 필수 여부, 기본값 등을 지정할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
| const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true
},
email: {
type: String,
required: true,
validate: {
validator: function(v) {
return /\S+@\S+\.\S+/.test(v);
},
message: props => `${props.value}는 유효한 이메일 형식이 아닙니다!`
}
},
age: {
type: Number,
min: 18,
max: 100
},
createdAt: {
type: Date,
default: Date.now
}
});
|
모델 (Model)#
스키마를 기반으로 생성되는 데이터베이스 컬렉션의 인터페이스.
1
| const User = mongoose.model('User', userSchema);
|
도큐먼트 (Document)#
MongoDB의 단일 레코드를 나타내는 인스턴스.
1
2
3
4
5
6
7
| const newUser = new User({
username: 'johndoe',
email: 'john@example.com',
age: 30
});
await newUser.save();
|
Mongoose의 주요 기능#
데이터 CRUD 작업#
생성 (Create)
1
2
3
4
5
6
7
8
9
10
11
12
| // 단일 도큐먼트 생성
const user = new User({
username: 'alice',
email: 'alice@example.com'
});
await user.save();
// 여러 도큐먼트 생성
await User.create([
{ username: 'bob', email: 'bob@example.com' },
{ username: 'charlie', email: 'charlie@example.com' }
]);
|
읽기 (Read)
1
2
3
4
5
6
7
8
| // 모든 사용자 조회
const users = await User.find();
// 조건부 조회
const youngUsers = await User.find({ age: { $lt: 30 } });
// 단일 사용자 조회
const user = await User.findById('user_id');
|
업데이트 (Update)
1
2
3
4
5
6
7
8
9
10
11
| // 단일 도큐먼트 업데이트
await User.updateOne(
{ username: 'johndoe' },
{ age: 31 }
);
// 여러 도큐먼트 업데이트
await User.updateMany(
{ age: { $lt: 30 } },
{ $inc: { age: 1 } }
);
|
삭제 (Delete)
1
2
3
4
5
| // 단일 도큐먼트 삭제
await User.deleteOne({ username: 'johndoe' });
// 여러 도큐먼트 삭제
await User.deleteMany({ age: { $lt: 25 } });
|
고급 쿼리 기능#
복잡한 쿼리
1
2
3
4
5
| const complexQuery = await User.find()
.where('age').gte(18)
.where('username').regex(/^john/)
.sort('-createdAt')
.limit(10);
|
가상 속성 (Virtual Properties)
1
2
3
| userSchema.virtual('fullName').get(function() {
return `${this.firstName} ${this.lastName}`;
});
|
미들웨어
1
2
3
4
5
6
7
| userSchema.pre('save', function(next) {
// 저장 전 비밀번호 해시
if (this.isModified('password')) {
this.password = bcrypt.hashSync(this.password, 10);
}
next();
});
|
Mongoose 연결 설정#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| const mongoose = require('mongoose');
async function connectDatabase() {
try {
await mongoose.connect('mongodb://localhost:27017/myapp', {
useNewUrlParser: true,
useUnifiedTopology: true
});
console.log('MongoDB에 성공적으로 연결되었습니다.');
} catch (error) {
console.error('데이터베이스 연결 실패:', error);
}
}
connectDatabase();
|
학습 로드맵#
- JavaScript 기본 문법 숙달
- Node.js 기초 학습
- MongoDB 기본 개념 이해
- Mongoose 기본 CRUD 작업 연습
- 고급 Mongoose 기능 탐구
Mongoose 사용 방법#
설치:
연결:
1
2
| const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydb');
|
스키마 정의:
1
2
3
4
5
| const userSchema = new mongoose.Schema({
name: String,
email: { type: String, required: true },
age: Number
});
|
모델 생성:
1
| const User = mongoose.model('User', userSchema);
|
CRUD 작업:
- 생성:
User.create()
- 읽기:
User.find()
- 수정:
User.updateOne()
- 삭제:
User.deleteOne()
참고 및 출처#
Mongoose ODM v8.9.0