몽고디비 기본 사용법과 데이터 조회





  • connect : 몽고디비 데이터 베이스 서버에 접속

  • collection : 컬렉션 참조( 테이블 참조와 유사)

  • find : 문서(데이터) 찾기




몽고 db 서버를 띄우기  


mongod --dbpath 원하는경로








다음처럼 데이터 값을 추가합니다





데이터가 잘 들어갔는지 확인




이것을 웹 서버에서 조회해서 존재한다면 로그인 성공으로 간주 그렇지 않으면 다시 로그인 화면으로 오는 웹 서버를 만들어보겠습니다






로그인 처리 화면



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
 
<html>
<head>
    <meta charset="utf-8" />
    <title>login2</title>
</head>
<body>
 
    <h1>login2</h1>
    <form method="post" action="/process/Login">
        <table>
            <tr>
                <td><label>ID : </label></td>
                <td><input type="text" name="id"></td>
            </tr>
            <tr>
                <td><label>PW : </label></td>
                <td><input type="text" name="passwords"></td>
 
 
            </tr>
 
            <tr>
                <td><input type="submit" value="Sumit" name=""></td>
            </tr>
 
        </table>
 
    </form>
 
</body>
</html>


login.html



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
 
<html>
<head>
    <meta charset="utf-8" />
    <title>404 Error</title>
</head>
<body>
    <h3>404 Error</h3>
    <br />
 
    <p>Can not find a page</p>
 
    <a href="/"> Home  </a>
</body>
</html>


404.html
오류페이지 처리를 위한 html






서버코드 (nodejs)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
var express = require('express');
var http = require('http');
var serveStatic = require('serve-static');      //특정 폴더의 파일들을 특정 패스로 접근할 수 있도록 열어주는 역할
var path = require('path');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var expressErrorHandler = require('express-error-handler');
 
var mongoClient = require('mongodb').MongoClient;
 
 
 
var database;
 
//몽고디비에 연결 ,  보통 웹서버 만든 직후 연결 , DB 먼저 연결 되도 상관 없음
//먼저 db를 가져온다 
function connectDB()
{
    //localhost 로컬 호스트
    //:27017  몽고디비 포트
    //local db 생성시 만든 폴더 명
    var databaseURL = 'mongodb://localhost:27017';
    mongoClient.connect(databaseURL,
        function (err, db)
        {
            if (err)
            {
                console.log('db connect error');
                return;
            }
 
            console.log('db was connected : ' + databaseURL);
            database = db;          //이 구문까지 실행되었다면 ongoDB 에 연결된 것
        }
    );
 
}
 
 
 
 
 
var app = express();      //express 서버 객체
 
 
app.set('port'3000);
app.use('public', serveStatic(path.join( __dirname, 'public')));
 
 
 
var bodyParser_post = require('body-parser');       //post 방식 파서
//post 방식 일경우 begin
//post 의 방식은 url 에 추가하는 방식이 아니고 body 라는 곳에 추가하여 전송하는 방식
app.use(bodyParser_post.urlencoded({ extended: false }));            // post 방식 세팅
app.use(bodyParser_post.json());                                     // json 사용 하는 경우의 세팅
//post 방식 일경우 end
 
 
//루트 경로 세팅
app.use(serveStatic(path.join(__dirname, 'public')));
 
 
//쿠키와 세션을 미들웨어로 등록한다
app.use(cookieParser());
 
//세션 환경 세팅
//세션은 서버쪽에 저장하는 것을 말하는데, 파일로 저장 할 수도 있고 레디스라고 하는 메모리DB등 다양한 저장소에 저장 할 수가 있는데
app.use(expressSession({
    secret: 'my key',           //이때의 옵션은 세션에 세이브 정보를 저장할때 할때 파일을 만들꺼냐 , 아니면 미리 만들어 놓을꺼냐 등에 대한 옵션들임
    resave: true,
    saveUninitialized: true
}));
 
 
 
 
//라우트를 미들웨어에 등록하기 전에 라우터에 설정할 경로와 함수를 등록한다
//
//라우터를 사용 (특정 경로로 들어오는 요청에 대하여 함수를 수행 시킬 수가 있는 기능을 express 가 제공해 주는것)
var router = express.Router();
 
//로그인 처리
router.route('/process/login').post(
    function (req, res)
    {
        console.log('process/login 호출됨');
        var paramID = req.body.id || req.query.id;
        var paramPW = req.body.passwords || req.query.passwords;
        console.log('paramID : ' + paramID + ', paramPW : ' + paramPW);
 
        if (database)
        {
            authUser(database, paramID, paramPW,
                function (err, docs)
                {
                    if (database)
                    {
                        if (err)
                        {
                            console.log('Error!!!');
                            res.writeHead(200, { "Content-Type""text/html;characterset=utf8" });
                            res.write('<h1>에러발생</h1>');
                            res.end();
                            return;
                        }
 
                        if (docs)
                        {
                            console.dir(docs);
                            res.writeHead(200, { "Content-Type""text/html;characterset=utf8" });
                            res.write('<h1>Login Success</h1>');
                            res.write('<h1> user </h1>' + docs[0].name);
                            res.write('<br><a href="/login.html"> re login </a>');
                            res.end();
 
                        }
                        else
                        {
                            console.log('empty Error!!!');
                            res.writeHead(200, { "Content-Type""text/html;characterset=utf8" });
                            res.write('<h1>user data not exist</h1>');
                            res.write('<a href="/login.html"> re login</a>');
                            res.end();
                        }
 
                    }
                    else
                    {
                        console.log('empty Error!!!');
                        res.writeHead(200, { "Content-Type""text/html;characterset=utf8" });
                        res.write('<h1>databasae 연결 안됨</h1>');
                        res.end();
                    }
                    
                    
 
                }
            );
        }
    }
);
 
 
//라우터 미들웨어 등록하는 구간에서는 라우터를 모두  등록한 이후에 다른 것을 세팅한다
//그렇지 않으면 순서상 라우터 이외에 다른것이 먼저 실행될 수 있다
app.use('/', router);       //라우트 미들웨어를 등록한다
 
 

//로그인 확인
var authUser = function (db, id, password, callback)
{
    console.log('input id :' + id + '  :  pw : ' + password);
 
    //cmd 에서 db.users  로 썻던 부분이 있는데 이때 이 컬럼(테이블)에 접근은 다음처럼 한다
    var users = db.db('test').collection("users");
 
    //찾고자 하는 정보를 입력해준다
    //var result = users.find({ name: id, passwords: password });
    //var result = users.find({ "name": id, "passwords":password });
    var result = users.find({ "name": id, "passwords"parseInt(password) });
    //var result = users.find({});
 
    result.toArray(
        function (err, docs)
        {
            if (err) {
                callback(err, null);
                return;
            }
 
            if (docs.length > 0)
            {
                console.log('find user [ ' + docs + ' ]');
                callback(null, docs);
            }
            else
            {
                console.log('can not find user [ ' + docs + ' ]');
                callback(nullnull);
            }
        }
    
    );
    
};
 
 
var errorHandler = expressErrorHandler(
    { static: { '404''./public/404.html' } }              //404 에러 코드가 발생하면 해당 페이지를 보여주는 예외 미들웨어
);
 
app.use(expressErrorHandler.httpError(404));
app.use(errorHandler );
 
//웹서버를 app 기반으로 생성
var appServer = http.createServer(app);
appServer.listen(app.get('port'),
    function () {
        console.log('express 웹서버 실행' + app.get('port'));
        connectDB();        //DB 연결 , DB 연결 먼저해도 상관 없음
    }
);
 




반응형

+ Recent posts