개발이야기/Node.js

(Mac) Node.js 몽고디비 연동 - 3. Mongoose 사용

C.엠케이 2021. 4. 14. 21:36

mongoose 모듈 설치

% npm install mongoose --save

 

mongoose 모듈 불러오기

var mongoose = requrire('mongoose');

 

mongoDB 연결 셋업

mongoDB는 서버 시작 시 default 로 27017 port 를 사용하고 있으니 참고하자.

 

> 변수 선언

// 데이터베이스 객체를 위한 변수 선언
var database;

// 데이터베이스 스키마 객체를 위한 변수 선언
var UserSchema;

// 데이터베이스 모델 객체를 위한 변수 선언
var UserModel;

> DB 연결 함수

// 데이터베이스에 연결
function connectDB(){
    // 데이터베이스 연결 정보
    var databaseUrl = 'mongodb://localhost:27017/local';

    // 데이터베이스 연결
    console.log('데이터베이스 연결을 시도합니다.');
    mongoose.Promise = global.Promise;
    mongoose.connect(databaseUrl, {useNewUrlParser: true, useUnifiedTopology: true});
    database = mongoose.connection;

    database.on('error', console.error.bind(console, 'mongoose connection error'));
    database.once('open', function(){
        console.log('데이터베이스에 연결되었습니다. : ' + databaseUrl);

        // 스키마 정의
        UserSchema = mongoose.Schema({
            id : String,
            name : String,
            password : String
        });
        console.log('UserSchema 정의함.');

        //UserModel 모델 정의
        UserModel = mongoose.model('users', UserSchema);
        console.log('UserModel 정의함.');
    });

    // 연결 끊어졌을 때 5초 후 재연결
    database.on('disconnected', function(){
        console.log('연결이 끊어졌습니다. 5초 후 다시 연결합니다.');
        setInterval(connectDB, 5000);
    });
    
}

 

mongoose 로 사용자 인증하기

간단하게 Client 에서 id, password 를 전달받은 뒤 DB에 해당 값이 있는 지 확인해보자.

// 사용자 인증하는 함수
var authUser = function(database, id, password, callback) {
    console.log('authUser 호출됨 : ' + id + ', ' + password);

    // 아이디와 비밀번호를 사용해 검색
    UserModel.find({"id" : id, "password" : password}, function(err, results){
        if(err) {
            callback(err, null);
            return;
        }

        console.log('아이디 [%s], 비밀번호 [%s]로 사용자 검색 결과', id, password);
        console.dir(results);

        if(results.length > 0){
            console.log('일치하는 사용자 찾음.', id + ', ' + password);
            callback(null, results);
        } else {
            console.log('일치하는 사용자를 찾지 못함.');
            callback(null, null);
        }
    });
    
};

 

> Client 소스

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>로그인 테스트</title>
    </head>
    <body>
        <h1>로그인</h1>
        <br>
        <form method="post" action="/process/login">
            <table>
                <tr>
                    <td><label>아이디</label></td>
                    <td><input type="text" name="id"></td>
                </tr>
                <tr>
                    <td><label>비밀번호</label></td>
                    <td><input type="password" name="password"></td>
                </tr>
            </table>
            <input type="submit" value="전송" name="">
        </form>
    </body>
</html>

 

> 전송 버튼 클릭 시 호출 Method

authUser 함수가 어떻게 사용되는 지 확인해보자.

// 라우팅 함수 등록
router.route('/process/login').post(function(req,res){
    console.log('/process/login 처리함.');

    var paramId = req.body.id;
    var paramPassword = req.body.password;

    if(database){
        authUser(database, paramId, paramPassword, function(err, docs){
            if(err) {throw err;}

            if(docs){
                console.dir(docs);

                res.writeHead('200', {'Content-Type':'text/html;charset=utf-8'});
                res.write('<h1>로그인 성공</h1>');
                res.write('<div><p>Param id : ' + paramId + '</p></div>');
                res.write('<div><p>Param password : ' + paramPassword + '</p></div>');
                res.write("<br><br><a href='/public/login.html'>다시 로그인하기</a>");
                res.end();

            } else {

                res.writeHead('200', {'Content-Type':'text/html;charset=utf-8'});
                res.write('<h1>로그인 실패</h1>');
                res.write('<div><p>아이디와 비밀번호를 다시 확인하십시오.</p></div>');
                res.write('<div><p>Param password : ' + paramPassword + '</p></div>');
                res.write("<br><br><a href='/public/login.html'>다시 로그인하기</a>");
                res.end();
            }
        })
    } else {
        res.writeHead('200', {'Content-Type':'text/html;charset=utf-8'});
                res.write('<h2>데이터베이스 연결 실패</h2>');
                res.write('<div><p>데이터베이스에 연결하지 못했습니다.</p></div>');
                res.end();
    }
});