우선 NOSQL의 장점은 느슨한 스키마라고 뽑을 수 있는데 하지만 너무 자유분방한 스키마는 에러를 불러오게 되니까 어느정도 스키마를 따르게 하는 작업이 필요하다.
스키마를 만들건데 여기서 스키마란 데이터를 어떻게 넣을지에 대한 청사진이라고 생각하면 된다.
root 경로 - models에 파일을 하나 만든다.
파일이름은 place.js라고 이름을 지어준다.
// place.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const placeSchema = new Schema({
title: { type: String, required: true },
description: { type: String, required: true },
image: { type: String, required: true },
address: { type: String, required: true },
location: {
lat: { type: Number, required: true },
lng: { type: Number, required: true },
},
creator: { type: String, required: true },
});
module.exports = mongoose.model("Place", placeSchema);
여기서 중요한 점은 new Schema를 해준 placeSchema에서 객체 안에 키값 안에 들어있는 코드들이다.
type은 키값이 가지는 value의 타입을 말하고 required는 필수인지 아닌지를 알려준다.
location에 있는 부분은 중첩스키마로 mongoose에서는 자동으로 중첩스키마를 인식한다.
컨트롤러 부분에서 스키마를 이용해서 데이터를 저장하는 방법이다.
const Place = require("2번에 만들었던 스키마 경로")
const createData = async(req, res, next) => {
const { title, description, address, creator } = req.body;
const createdData = new Place({
title,
description,
address,
location,
image,
creator
})
try{
await createdData.save()
} catch(err){
const error = new HttpError("에러", 500)
return next(error)
}
res.status(201).json({createdData})
}
2번에서 만든 스키마를 임포트 해준 뒤 new Place를 이용해서 데이터를 생성하고
성공하면 생성된 데이터에 save()메서드를 이용해서 db에 저장하도록 한다.