728x90
반응형
SMALL
Do it! Node.js 프로그래밍 입문 8일차 입니다.
DB모델에서 사용하는 함수
controllers/contactController.js
아래 코드 추가
const Contact = require("../models/contactModel") // DB모델 연결
create()
DB에 새로운 도큐먼트를 생성합니다.
Contact.create({name, email, phone})
find()
지정한 조건에 맞는 도큐먼트를 찾습니다. 조건을 따로 지정하지 않으면 모든 도큐먼트를 찾습니다.
Contact.find()
updateOne, updateMany
updateOne는 조건에 맞는 첫 번째 도큐먼트만 업데이트하고 updateMany는 조건에 맞는 모든 도큐먼트를 업데이트합니다.
Contact.updateOne({name: 'Kim'}, {phone: '1234'})
deleteOne, deleteMany
update와 동일한데 업데이트가 아닌 삭제를 합니다.
Contact.deleteOne()
findById
아이디 값을 기준으로 도큐먼트를 찾습니다.
Contact.findById(id)
findByIdAndUpdate, findByIdAndDelete
Contact.findByIdAndUpdate(
id,
{name, email, phone},
{new: true}
)
// 삭제할때는 id값만 지정
Contact.findByIdAndDelete(id)
findByIdAndUpdate, findByIdAndDelete를 사용해서 한번에 수정, 삭제를 할 수 있지만 findById를 사용해서 먼저 id값을 도큐먼트에서 찾고 수정하거나 삭제하기 전에 도큐먼트의 유효성을 검사하는 것처럼 다른 작업을 추가할 수 있습니다. findById만 사용할 경우에는 특정 정보를 가져와서 수정한 후에 save함수를 직접 사용해서 저장해야 합니다.
최종코드
const asyncHandler = require("express-async-handler") // npm install express-async-handler
const Contact = require("../models/contactModel") // DB모델 연결
// @desc 함수설명
// @route 요청방식과 URL
// @desc Get all contacts
// @route GET /contacts
// const getAllContacts = async (req, res) => { // 비동기 처리
// try {
// res.status(200).send("Contacts Page")
// } catch (error) {
// res.send(error.message)
// }
// }
// => 위의 코드 express-async-handler를 사용하여 수정
const getAllContacts = asyncHandler(async (req, res) => { // 비동기 처리
// DB 연락처 가져오기
const contacts = await Contact.find()
res.status(200).send(contacts)
})
// @desc Create a contact
// @route POST /contacts
const createContact = asyncHandler(async (req, res) => {
console.log(req.body)
const {name, email, phone} = req.body
if(!name || !email || !phone) {
return res.status(400).send("필수 값이 입력되지 않았습니다.")
}
const contact = await Contact.create({name, email, phone})
res.status(201).send("Create Contacts")
})
// @desc Get a contact
// @route Get /contacts/:id
const getContact = asyncHandler(async (req, res) => {
const name = req.params.id
const contact = await Contact.findOne({name: name})
res.status(200).send(contact)
})
// @desc Update a contact
// @route PUT /contacts/:id
const updateContact = asyncHandler(async (req, res) => {
// 특정조건에 맞는 연락처 가져오기
const id = req.params.id
const {name, email, phone} = req.body
// const contact = await Contact.findById(id)
// if(!contact) {
// res.status(404)
// throw new Error("Contact not found")
// }
// contact.name = name
// contact.email = email
// contact.phone = phone
// contact.save() // findById()를 사용할 경우 save()를 꼭 해줘야 한다
// res.status(200).json(contact)
// findByIdAndUpdate() 사용
const updateContact = await Contact.findByIdAndUpdate(
id,
{name, email, phone},
{new: true}
)
res.status(200).send(updateContact)
})
// @desc Delete a contact
// @route DELETE /contacts/:id
const deleteContact = asyncHandler(async (req, res) => {
// const contact = await Contact.findById(req.params.id)
// if(!contact) {
// res.status(404)
// throw new Error("Contact not found")
// }
// await Contact.deleteOne()
// res.status(200).send(`Delete Contact for ID : ${req.params.id}`)
const id = req.params.id
const contact = await Contact.findByIdAndDelete(id)
res.status(200).send(contact)
})
module.exports = {getAllContacts, createContact, getContact, updateContact, deleteContact}
728x90
반응형
LIST
'Node.js' 카테고리의 다른 글
[Node.js] 노드제이에스 - 폼에서 라우트 처리 (0) | 2024.02.13 |
---|---|
[Node.js] 노드제이에스 - 템플릿 엔진 (2) | 2024.02.13 |
[Node.js] 노드제이에스 - 컨트롤러 작성 (0) | 2024.02.10 |
[Node.js] 노드제이에스 - CRUD를 위한 API 작성 (0) | 2024.02.10 |
[Node.js] 노드제이에스 - 몽고DB (2) | 2024.02.09 |