Mongoose 스키마 설정
2024. 1. 14. 18:20ㆍMERN
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)
// Model은 나중에 생성자 함수를 반환함
// 1번째 인자 - 모델의 이름
// 2번째 인자 - 모델에 참조할 스키마
생성한 스키마를 통해 불러와서 데이터 집어 넣기
const createPlace = (req,res,next)=>{
const errors = validationResult(req);
if (!errors.isEmpty()){
console.log(errors);
res.status(errors);
throw new HttpError("Invalid INput",422);
}
const {title,description,location,address,creator} = req.body;
// const title = req.body.title
// mongoDB 연결 후 필요 없는 부분
// const createdPlace = {
// id : uuid(),
// title,
// description,
// location,
// address,
// creator
// }
let coordinates;
try {
coordinates = await getCoordsForAddress(address);
} catch (error) {
return next(error);
}
const createdPlace = new Place({
title,
description,
location: coordinates,
image: "https://www.hyundai.co.kr/image/upload/asset_library/MDA00000000000034228/25725e75e9744abf857242a28b8d3f9e.jpg",
creator
});
try{
await createdPlace.save();
}catch (err){
const error = new HttpError(
"Creating Place error",500
);
return next(error); // 오류 시 프로그램 종료
}
// Save는 Mongoose 메소드이며, 컬렉션 데이터베이스에 새 문서를 저장할 때 필요한 MongoDB 코드를 처리해줌
// 고유 ID도 생성해 줌
// 또한 save는 프로미스고, 비동기식 작업이 있음. 얘를 담고 있는 함수는 aync 그리고 앞에 await를 붙여야 함
// 또 에러가 났을 때를 고려하여 코드 작성
DUMMY_PLACES.push(createdPlace);
res.status(201).json({place: createdPlace})
// res.status(201).jso
'MERN' 카테고리의 다른 글
Mongoose 스키마 설정 (0) | 2024.01.14 |
---|---|
백엔드(Node) & MongoDB(데이터베이스) 연결 (3) | 2024.01.14 |
Mongoose (MongoDB - DB 생성, 조회) (0) | 2024.01.12 |
백엔드 MongoDB 데이터 베이스에 연결하기 (Mongoose 사용) (0) | 2024.01.10 |
MongoDB 연결, 시작2 (0) | 2024.01.10 |