Mongoose의 모든것은 스키마로 부터 파생된다.
무려 Mongoose공식문서에 있는 말이다.
물론 NoSQL에서 스키마를 사용하지 않고 DB를 저장하기때문에 유연한 점이 장점이었지만
db에 들어갈 데이터 형식을 미리 짜놔야지 코드작성 + 관리에 유용하다.
import mongoose from "mongoose"
//new Schema
const mySchema = new mongoose.Schema({
title:String,
content:[String],
createdAt:Date
})
타입을 넣는 방법이 2가지인데 직접선언 / "type"프로퍼티가 들어간 object를 선언 이있다.
//직접선언
schema = new Schema({
test:String
})
// type프로퍼티 object
schema = new Schema({
test:{type:String}
})
후자의 방법이 있는거때문에 type이 들어간 객체를 선언하고싶을때는 살짝 귀찮지만 다음의 방법을 따라야한다
const chema = new Schema({
test: {
type: String,
ticker: String
}
//안될거다 type 프로퍼티가 들어간 객체로 타입을 선언한것처럼.
mongoose가 인식해서 test는 단일 문자열의 타입을 받는다고 이해할거다
const chema = new Schema({
test:{
type:{type:String},
ticker:String
}
})
//이런식으로 해야할거다. 이해가 될거다
후자의 방법은 type프로퍼티 뿐만 아니라 추가적인 프로퍼티를 써서 다른 기능적인부분을 넣어줄수 있다.
schema = new Schema({
test:{
type:String,
required:true
}
})
꽤 많은 기능이 있으니 (ex:required일 경우 validate함수 추가) 공식문서를 봐보자.
const Model = mongoose.model('modelName',mySchema)
모델은 맨앞글자가 UpperCase인게 국룰이란다.
모델까지 만들었으니 이 모델을 이용해 mongoose로 document를 생성해줄거다. 방법은 2가지다 new 키워드와 create메서드.
import {Model} from "./models"
// Model이 만들어진 스키마를 따라야겠지? 당연히?
const document = new Model({
title:"my first document",
content: ['content'],
createdAt:Date.now()
})
document.save(); //return Promise
//example in express
async function postController(req,res){
const document = new Model({...})
await document.save()
//db에 저장이 완료되고 나면 그제서야 response 할거다.
return res.send('complete')
}
import {Model} from "./models"
Model.create({
title:"my first document",
content: ['content'],
createdAt:Date.now()
})
끝이다. 얘는 new Model({}).save()와 동일하기 때문에 따로 save()할 필요는 없지만 마찬가지로 promise를 리턴하기때문에 안전한 response를 위해선 example코드와 비슷하게 써주면 될거같다.