기술 스택
- Express.js, MongoDB
패키지 설치
- express: Node.js 서버 프레임워크.
- body-parser: 요청 본문 파싱.
- mongoose: MongoDB와 Node.js 연결.
- dotenv: 환경변수 관리.
MongoDB
MongoDB: 개발자 데이터 플랫폼
업계를 선도하는 모던 데이터베이스를 토대로 구축된 애플리케이션 데이터 플랫폼을 사용해 아이디어를 더욱 빠르게 실현하세요. MongoDB는 데이터를 손쉽게 처리할 수 있도록 지원합니다.
www.mongodb.com
- mongoDB 계정생성 후 연동
- 프로젝트 생성 & Cluster 생성
- app.js 또는 server.js 설정
// 미들웨어 설정
app.use(require('body-parser').json());
// mongoose 연동
const mongoose = require('mongoose');
// mongodb atlas -> Application Development → Get conntection string에서 확인한 연동 url
const uri = "mongodb+srv://~~";
const clientOptions = { serverApi: { version: '1', strict: true, deprecationErrors: true } };
async function run() {
try {
// Create a Mongoose client with a MongoClientOptions object to set the Stable API version
await mongoose.connect(uri, clientOptions);
await mongoose.connection.db.admin().command({ ping: 1 });
console.log("Pinged your deployment. You successfully connected to MongoDB!");
} finally {
// Ensures that the client will close when you finish/error
// await mongoose.disconnect();
}
}
run().catch(console.dir);
- 연동시 허용되지 않는 IP오류 발생시엔 mongodb → altas → nextwork access에서 모든 IP를 허용가능. (그러나 보안성이 떨어지므로 비추천)
Getting Started With MongoDB & Mongoose | MongoDB
Learn how Mongoose, a library for MongoDB, helps you structure and access data with ease. Mongoose is “elegant MongoDB object modeling for Node.js."
www.mongodb.com
TODO CURD
- app.js에서 사용할 js 바인딩
// app.js에 todoRoutes.js 라우터 바인딩
app.use('/todo', require('./routes/todoRoutes'));
- todo curd 스크립트 작성
// todo.js
var express = require('express');
const Todo = require('../models/Todo');
var router = express.Router();
// read all
router.get("/", async (req,res) => {
try{
const todos = await Todo.find();
res.status(200).json(todos);
} catch(err){
res.status(500).json({error:err.message});
}
});
// create
router.post("/", async (req,res) => {
try{
const newTodo = new Todo({
title:req.body.title
});
const savedTodo = await newTodo.save();
res.status(201).json(savedTodo);
} catch(err){
res.status(400).json({error:err.message});
}
});
// update
router.put("/:id", async (req,res) => {
try{
const updatedTodo = await Todo.findByIdAndUpdate(
req.params.id,
{ $set: req.body },
{ new: true }
);
res.status(200).json(updatedTodo);
} catch(err){
res.status(400).json({error:err.message});
}
});
// delete
router.delete("/:id", async (req,res) => {
try{
const updatedTodo = await Todo.findByIdAndDelete(req.params.id);
res.status(200).json({ message: 'Todo deleted' });
} catch(err){
res.status(400).json({error:err.message});
}
});
module.exports = router;
테스트
- 조회 테스트는 브라우저를 통해 확인
- post, put, delete 는 postman을 통해서 확인함.
'Script > Node.js' 카테고리의 다른 글
[Node.js] Node.js Restful API Example (0) | 2025.01.13 |
---|---|
[Node.js] Node.js 유용한 패키지들 (0) | 2025.01.13 |
[Node.js] Node.js EJS 템플릿 적용 (0) | 2025.01.06 |
[Node.js] 간단한 Node.js API Server 셋팅하기 (0) | 2025.01.03 |
[Node.js] Node.js 시작하기 (0) | 2025.01.02 |