mongoose를 사용하여 MongoDB에 데이터를 생성하고 조회하기 위해 다음과 같은 폴더 구조로 NodeJS 프로젝트를 만들었다.
src
|- api
| |- index.js
|- posts
| |- index.js
| |- posts.ctrl.js
|- models
| |- post.js
|-app.js
src/app.js
const express = require('express')
const bodyParser = require('body-parser');
const api = require('./api');
const app = express()
const port = 3000
const MONGO_URI = 'mongodb://localhost:27017/test_db';
const mongoose = require('mongoose');
mongoose.connect(MONGO_URI, {
useNewUrlParser: true,
useFindAndModify: false
}).then(() => {
console.log('Connected to MongoDB')
}).catch(e => {console.log(e);})
app.use(bodyParser.json());
app.use("/api", api);
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
src/models/post.js
const mongoose = require('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);
module.exports = Post;
src/api/index.js
const express = require("express");
const asyncify = require("express-asyncify");
const posts = require('./posts');
const api = asyncify(express.Router());
api.use("/posts", posts);
module.exports = api;
src/api/posts/index.js
const express = require("express");
const asyncify = require("express-asyncify");
const postsCtrl = require("./posts.ctrl");
const posts = asyncify(express.Router());
posts.get("/", postsCtrl.list);
posts.post("/", postsCtrl.write);
posts.get("/:id", postsCtrl.read);
posts.delete("/:id", postsCtrl.remove);
posts.patch("/:id", postsCtrl.update);
module.exports = posts;
src/api/posts/posts.ctrl.js
const Post = require("../../models/post");
module.exports = {
// 데이터 생성
write: async (req, res ) => {
const {title, body, tags } = req.body;
// new 키워드를 사용하여 Post 인스턴스를 생성
const post = new Post({
title,
body,
tags,
})
try {
// save() 함수를 통해 데이터베이스에 저장시킴
await post.save();
return res
.status(200)
.json(post);
} catch(err) {
return res.status(500).json({error: err});
}
},
// 데이터 조회
list: async (req, res ) => {
try {
// find() 함수 사용, 이후 exec()를 붙여주어야 서버에 쿼리 요청
const posts = await Post.find().exec();
return res
.status(200)
.json(posts)
} catch(err) {
return res.status(500).json({error: err});
}
},
// 특정 id를 가진 포스트 조회
read: async (req, res ) => {
const { id } = req.params;
try {
// 특정 id를 가진 데이터를 조회할 때는 findById() 함수를 사용
// find() 함수와 마찬가지로 exec()를 붙여주어야 쿼리를 요청
const post = await Post.findById(id).exec();
if(!post) {
return res.status(404).end()
}else{
return res
.status(200)
.json(post)
}
} catch(err) {
return res.status(500).json({error: err});
}
},
remove: async (req, res ) => {},
update: async (req, res ) => {},
}