MongoDB

[MongoDB] - Mongoose 이용하여 데이터 삽입하기 (1)

Riucc 2018. 11. 23. 13:20

○ MongoDB Mongoose 이용하여 데이터 삽입하기 (1) 

 

// app.js


// Express 기본 모듈 불러오기
var express = require('express')
, http = require('http')
, path = require('path');

// Express의 미들웨어 불러오기
var static = require('serve-static')
var bodyParser = require('body-parser')

// mongoose 모듈 사용
var mongoose = require('mongoose');

// 익스프레스 객체 생성
var app = express()

// 기본 속성 설정
app.set('port', process.env.PORT || 3000);
// public 폴더를 static으로 오픈
app.use('/public', static(path.join(__dirname, 'public')));
// body-parser를 이용해 application/x-www-form-urlencoded 파싱
app.use(bodyParser.urlencoded({ extended: false }))
// body-parser를 이용해 application/json 파싱
app.use(bodyParser.json())

//===== 데이터베이스 연결 =====//
// 데이터베이스 객체를 위한 변수 선언
var database;
// 데이터베이스 스키마 객체를 위한 변수 선언
var UserSchema;
// 데이터베이스 모델 객체를 위한 변수 선언
var UserModel;

//데이터베이스에 연결
function connectDB() {
// 데이터베이스 연결 정보
// localhost:기본포트/데이터베이스명
    var databaseUrl = 'mongodb://localhost:27017/test';
    
    // 데이터베이스 연결
console.log('데이터베이스 연결을 시도합니다.');
// mongoose의 Promise 객체는 global의 Promise 객체 사용하도록 함
mongoose.Promise = global.Promise;
    mongoose.connect(databaseUrl, { useNewUrlParser: true });
    database = mongoose.connection;
    
    database.on('error', console.error.bind(console, 'mongoose connection error.'));    
    database.on('open', function () {
        console.log('데이터베이스에 연결되었습니다. : ' + databaseUrl);
        
        // 스키마 정의
        UserSchema = mongoose.Schema({
            email: String,
            password: String
        }, {versionKey: false}); // __v 삭제위해
        console.log('UserSchema 정의함.');
        
        // UserModel 모델 정의
        UserModel = mongoose.model("users", UserSchema);
        console.log('UserModel 정의함.');
        
    });
// 연결 끊어졌을 때 5초 후 재연결
    database.on('disconnected', function() {
console.log('연결이 끊어졌습니다. 5초 후 재연결합니다.');
setInterval(connectDB, 5000);
});
}

// 회원가입 데이터베이스
app.post('/process/signup', function(req,res) {
console.log('/process/signup 호출됨.');
    // 요청 파라미터 확인
var paramEmail = req.body.email || req.query.email;
var paramPassword = req.body.psw || req.query.psw;
console.log('요청 파라미터 : ' + paramEmail + ', ' + paramPassword);
// 데이터베이스 객체가 초기화된 경우, addUser 함수 호출하여 사용자 추가
    if (database) {
        addUser(database, paramEmail, paramPassword, function(err, addedUser) {
if (err) {throw err;}
// 결과 객체 있으면 성공 응답 전송
            if (addedUser) {
                console.dir(addedUser);
                res.writeHead('200', {'Content-Type':'text/html;charset=utf8'});
                res.write('<h2>사용자 추가 성공</h2>');
res.end();
} else { // 결과 객체가 없으면 실패 응답 전송
                res.writeHead('200', {'Content-Type':'text/html;charset=utf8'});
                res.write('<h2>사용자 추가 실패</h2>');
                res.end();
            }
});
} else { // 데이터베이스 객체가 초기화되지 않은 경우 실패 응답 전송
        res.writeHead('200', {'Content-Type':'text/html;charset=utf8'});
        res.write('<h2>데이터베이스 연결 실패</h2>');
        res.end();
    }
});

//사용자를 추가하는 함수
var addUser = function(database, email, password, callback) {
    console.log('addUser 호출됨 : ' + email + ', ' + password);
    
    // UserModel 인스턴스 생성
    var user = new UserModel({"email":email, "password":password});

    // save()로 저장 : 저장 성공 시 addedUser 객체가 파라미터로 전달됨
    user.save(function(err, addedUser) {
        if (err) {
            callback(err, null);
            return;
        }
    
     console.log("사용자 데이터 추가함.");
     callback(null, addedUser);
    });
};

//===== 서버 시작 =====//

// 프로세스 종료 시에 데이터베이스 연결 해제
process.on('SIGTERM', function () {
console.log("프로세스가 종료됩니다.");
app.close();
});

app.on('close', function () {
    console.log("Express 서버 객체가 종료됩니다.");
    if (database) {
        database.close();
    }
});

// Express 서버 시작
http.createServer(app).listen(app.get('port'), function(){
console.log('서버가 시작되었습니다. 포트 : ' + app.get('port'));

// 데이터베이스 연결을 위한 함수 호출
connectDB();
});


// public/singup.html


<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title>Document</title>

<style>
body {
font-family: Arial, Helvetica, sans-serif;
}

* {
box-sizing: border-box;
}

/* Full-width input fields */
input[type=text],
input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
display: inline-block;
border: none;
background: #f1f1f1;
}

/* Add a background color when the inputs get focus */
input[type=text]:focus,
input[type=password]:focus {
background-color: #ddd;
outline: none;
}

/* Set a style for all buttons */
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.9;
}

button:hover {
opacity: 1;
}

/* Extra styles for the cancel button */
.cancelbtn {
padding: 14px 20px;
background-color: #f44336;
}

/* Float cancel and signup buttons and add an equal width */
.cancelbtn,
.signupbtn {
float: left;
width: 50%;
}

/* Add padding to container elements */
.container {
padding: 16px;
}

/* The Modal (background) */
.modal {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
left: 0;
top: 0;
width: 100%;
/* Full width */
height: 100%;
/* Full height */
overflow: auto;
/* Enable scroll if needed */
background-color: #474e5d;
padding-top: 50px;
}

/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: 5% auto 15% auto;
/* 5% from the top, 15% from the bottom and centered */
border: 1px solid #888;
width: 80%;
/* Could be more or less, depending on screen size */
}

/* Style the horizontal ruler */
hr {
border: 1px solid #f1f1f1;
margin-bottom: 25px;
}

/* The Close Button (x) */
.close {
position: absolute;
right: 35px;
top: 15px;
font-size: 40px;
font-weight: bold;
color: #f1f1f1;
}

.close:hover,
.close:focus {
color: #f44336;
cursor: pointer;
}

/* Clear floats */
.clearfix::after {
content: "";
clear: both;
display: table;
}

/* Change styles for cancel button and signup button on extra small screens */
@media screen and (max-width: 300px) {

.cancelbtn,
.signupbtn {
width: 100%;
}
}
</style>
</head>

<body>
<h2>Modal Signup Form</h2>

<button onclick="document.getElementById('id01').style.display='block'"
style="width:auto;">Sign Up</button>

<div id="id01" class="modal">
<span onclick="document.getElementById('id01').style.display='none'" class="close"
title="Close Modal">&times;</span>
<form class="modal-content" action="/process/signup" method="POST">
<div class="container">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>

<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>

<div class="clearfix">
<button type="button" onclick="document.getElementById('id01')
.style.display='none'" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</div>

<script>
// Get the modal
var modal = document.getElementById('id01');

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>

</html>