1. 몽고디비 설치 및 연결
npm init
npm i mongoose
config / db.js 파일 생성
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI)
console.log(`MongoDB Connected : ${conn.connection.host}`.cyan.underline);
} catch (error) {
console.log(error);
process.exit(1);
}
}
module.exports = connectDB;
process.env.MONGO_URI 는 MongoDB 홈페이지에서 프로젝트랑 데이터베이스를 만들었으면
CONNECT가 활성되어 있을텐데 그중 Conncet your Aplication 을 클릭하면 관련 주소를 준다.
ex) MONGO_URI = mongodb+srv://hwanmin:<password>@hwanmincluster.ftxzg.mongodb.net/mernapp?retryWrites=true&w=majority
const express = require('express');
const dotenv = require('dotenv').config()
const connectDB = require('./config/db')
const app = express();
const PORT = process.env.PORT || 8000
connectDB();
app.use(express.json())
app.use(express.urlencoded({extended : true}))
app.use('/api/goals' , require('./router/goalRouter') )
app.listen( PORT , () => {
console.log(`-- ${PORT} 서버시작 --`);
} )
ConnectDB() 함수 실행 , DB가 연결되면 콘솔창에 뜬다.
2. 모델 스키마 생성
model / model.js 파일 생성
const mongoose = require('mongoose');
const goalSchema = mongoose.Schema({
text : {
type : String ,
required : [true , 'Please add a text value' ]
}
},
{
timestamps : true,
}
)
module.exports = mongoose.model('Goal' , goalSchema);
https://mongoosejs.com/docs/guide.html
Mongoose v6.2.1: Schemas
If you haven't yet done so, please take a minute to read the quickstart to get an idea of how Mongoose works. If you are migrating from 5.x to 6.x please take a moment to read the migration guide. Everything in Mongoose starts with a Schema. Each schema ma
mongoosejs.com
모델은 모델이름과 , 스키마를 정의해줘야 한다.
스키마 후에 timestamps는생성 시간을 알려준다.
3. 스키마 모델 사용한 CRUD
https://mongoosejs.com/docs/api/query.html
Mongoose v6.2.1:
Parameters [options] «Object» [model] «Object» [conditions] «Object» [collection] «Object» Mongoose collection Query constructor used for building queries. You do not need to instantiate a Query directly. Instead use Model functions like Model.find
mongoosejs.com
몽구스는 기본적으로 CRUD 쿼리를 지원한다.
const asyncHandler = require('express-async-handler')
const Goal = require('../model/goalModel');
const getGoals = asyncHandler (async (req,res) => {
const goals = await Goal.find()
res.status(200).json(goals)
})
const setGoal = asyncHandler (async (req,res) => {
if(!req.body.text) {
res.status(400)
throw new Error('Please add a text field')
}
const goal = await Goal.create({
text : req.body.text
})
res.status(200).json(goal)
})
const updateGoal = asyncHandler (async (req,res) => {
const goal = await Goal.findById(req.params.id)
if(!goal) {
res.status(400)
throw new Error('Goal not find')
}
const UpdateGoal = await Goal.findByIdAndUpdate(req.params.id , req.body , {new : true})
res.status(200).json(UpdateGoal)
})
const deleteGoal = asyncHandler (async (req,res) => {
const goal = await Goal.findById(req.params.id)
if(!goal) {
res.status(400)
throw new Error('Goal not find')
}
await goal.remove()
res.status(200).json({ id : req.body.params})
})
module.exports = {
getGoals,
setGoal,
updateGoal,
deleteGoal
}
필요한 쿼리는 상황에 맞게 가져다 쓰면 될거같다.