반응형
설치 명령어
brew tap mongodb/brew
brew install mongodb-community@7.0
brew services start mongodb-community@7.0
기본설정
import mongoose from 'mongoose';
const { PORT, MONGO_URI } = process.env;
mongoose
.connect(MONGO_URI)
.then(() => {
console.log('Connected to MongoDB');
})
.catch((e) => {
console.error(e);
});
// MONGO_URI 가 mongodb://localhost:27017/[테이블이름]
스키마 설정
import mongoose from 'mongoose';
const { Schema } = mongoose;
const PostSchema = new Schema({
title: String,
body: String,
tags: [String],
publishedDate: {
type: Date,
default: Date.now,
},
});
const Post = mongoose.model('Post', PostSchema);
export default Post;
CRUD
/*
POST /api/posts
{
title: '제목',
body: "내용",
tags: ['태그1', '태그2']
}
*/
export const write = async (ctx) => {
const { title, body, tags } = ctx.request.body;
const post = new Post({
title,
body,
tags,
});
try {
await post.save();
ctx.body = post;
} catch (e) {
ctx.throw(500, e);
}
};
/*
GET /api/posts
*/
export const list = async (ctx) => {
try {
const posts = await Post.find().exec();
ctx.body = posts;
} catch (e) {
ctx.throw(500, e);
}
};
/*
GET /api/posts/:id
*/
export const read = async (ctx) => {
const { id } = ctx.params;
try {
const post = await Post.findById(id).exec();
if (!post) {
ctx.status = 404;
return;
}
ctx.body = post;
} catch (e) {
ctx.throw(500, e);
}
};
728x90
'코딩 > Node.js' 카테고리의 다른 글
[koa] Import / export syntax 적용하기 (0) | 2024.12.09 |
---|---|
[koa] koa 학습하기 - 2 - 컨트롤러 적용 (0) | 2024.12.08 |
[koa] 코아 프레임워크 학습 - 1 - 라우팅 기능적용 (0) | 2024.12.08 |
[yarn] yarn 설치 불가 이슈(다층구조 충돌이슈) (0) | 2024.12.07 |
[NODE] JWT 기능 구현. (0) | 2024.11.01 |