몽구스 프로젝트는 몽고 디비 연결 및 스키마를 설정하는 모델인 Schema 폴더로 구성되어 있습니다.
위 그림은 연결을 담당하는 index.js 폴더와 users, room, posts, comments, bookmark 컬랙션으로 구성되어 있습니다.
$ npm i mongoose
몽구스의 index.js입니다. connect 부분은 노출이 되면 DB가 보안에 취약해 질 수 있으므로
dotenv를 사용하여 가려줍니다.
const mongoose = require("mongoose");
require("dotenv").config();
const connect = () => {
mongoose
.connect(process.env.DB_HOST)
.catch(err => console.log(err));
};
mongoose.connection.on("error", err => {
console.error("몽고디비 연결 에러", err);
});
module.exports = connect;
몽고디비의 컬랙션을 정의합니다. noSQL 몽고디비를 SQL스럽게 만들어주는것이라고 생각하면 됩니다.
const mongoose = require("mongoose");
const UsersSchema = new mongoose.Schema({
userId: {
type: String,
required: true,
unique: true,
},
nickName: {
type: String,
},
password: {
type: String,
},
phoneNumber : {
type : String,
},
age: {
type: String,
},
gender: {
type: String,
},
refresh_token : {
type : String,
},
admin : {
type : String,
},
bookmark: {
type: Array,
},
bookmarkData: {
type: Array,
},
verifyCode : {
type : String,
},
createdAt: {
type: String,
default: Date.now
},
updatedAt: {
type: String,
default: Date.now
},
});
module.exports = mongoose.model("Users", UsersSchema);
const express = require("express");
const app = express();
const connect = require("./schema");
connect();
app.use("/", routes);
app.listen(3000, () => {
console.log("3000번 포트로 열렸습니다");
});
const express = require('express');
const Users = require("../schema/users");
const Posts = require("../schema/posts");
const router = express.Router();
router.get("/", async(req,res) => {
await Users.find({});
res.send('유저 목록 불러오기')
}
module.exports = router;
각 필요한 스키마를 require 해서 불러올 수 있습니다.
populate는 몽구스의 핵심 요소로, 몽고디비 컬랙션 간에 동적관계를 맺어주는 역할을 합니다.
MySQL 의 JOIN 같은 역할이라고 볼 수 있다.
아니면
type에는 ObjectId를 ref에는 관계를 맺은 스키마를 적어준다.
만일 관계 데이터를 가져오고 싶다면, 뒤에 populate를 명시해서 Document를 임베디드 시켜준다.