-
[MongoDB] 스키마와 모델DB/MongoDB 2022. 10. 12. 22:48
스키마
- 해당 컬렉션의 문서에 어떤 종류의 값이 들어가는지를 정의
- MongoDB에 저장되는 document의 Data 구조 즉 필드 타입에 관한 정보를 JSON 형태로 정의한 것으로 RDBMS의 테이블 정의와 유사한 개념
- type(데이터 타입), required(필수 여부), unique(중복 x)
// 스키마 정의 const userSchema = new mongoose.Schema({ email: { type: String, required: true, unique: true }, username: { type: String, required: true, unique: true }, password: { type: String, required: true }, name: { type: String, required: true }, location: String, });
데이터 타입
Data TypeDescription String 표준 자바스크립트와 Node.js의 문자열 type Number 표준 자바스크립트와 Node.js의 숫자 type Boolean 표준 자바스크립트와 Node.js의 불리언 type Buffer Node.js의 binary type(이미지, PDF, 아카이브 등) Date ISODate format data type(2016-08-08T12:52:30:009Z) Array 표준 자바스크립트와 Node.js의 배열 type Schema.types.ObjectId 12byte binary 숫자에 대한 MongoDB 24자리 hex 문자열(501d86090d371bab2c0341c5) Schema.types.Mixed 모든 유형의 데이터 모델
- 모델을 이용하여 데이터베이스에 실제 작업할 수 있음(조회, 추가, 수정, 삭제)
const User = mongoose.model('User', userSchema);
Middlewares
- MongoDB에서 특정 작업(저장 등)이 실행되기 전/후에 실행되는 함수
- 다음 예시는 비밀번호를 DB에 저장하기 전에 비밀번호를 암호화 시키는 코드
- 스키마.pre(특정 작업, 수행 함수)
userSchema.pre('save', async function(){ console.log("users password: ", this.password); this.password = await bcrypt.hash(this.password, 5); console.log("hash password: ", this.password); });
DB저장
- 모델.create
const {name, email, username, password, location} = req.body; await User.create({ name, email, username, password, location, });
models/User.js
import bcrypt from "bcrypt"; import mongoose from "mongoose"; const userSchema = new mongoose.Schema({ email: { type: String, required: true, unique: true }, username: { type: String, required: true, unique: true }, password: { type: String, required: true }, name: { type: String, required: true }, location: String, }); userSchema.pre('save', async function(){ console.log("users password: ", this.password); this.password = await bcrypt.hash(this.password, 5); console.log("hash password: ", this.password); }); const User = mongoose.model('User', userSchema); export default User;
728x90'DB > MongoDB' 카테고리의 다른 글
[MongoDB] 몽고디비 명령어(Command) (0) 2022.10.10