[WebApp / Express] 간단한 MongoDB Middleware 만들기

이번 글에서는 MongoDB의 ODM(Object Data Mapping) 툴인 mongoose를 이용하여 간단한 MongoDB Middleware를 만들어 보도록 한다.

 

 

 

Part 1 - Express 프로젝트 생성

우선 Express 프로젝트를 생성한다:

 

$ express my-project && cd my-project

 

생성된 프로젝트 경로에 mongoose ODM을 설치한다:

 

$ npm install mongoose

 

app.js에서 Server를 생성한다 (포트번호는 3000으로 지정하였다):

 

[{EXPRESS_ROOT}/app.js]

 

1
2
3
4
5
6
7
8
//////////////////////////////////////////////////////
// ------- creates Server -------
// port setup
app.set('port', process.env.PORT || 3000);
  
var server = app.listen(app.get('port'), function() {
  console.log('Express server listening on port ' + server.address().port);
});

 

 

 

 

Part 2 - mongoose connection 설정

Mongoose Connection을 하기에 앞서 MongoDB를 실행한다. 예를 들어, Terminal을 실행하여 다음 명령을 입력한다:

 

$ mongod --dbpath {YOUR_DB_PATH}

 

우선 mongoose를 로딩하고, Mongoose Connection을 위해 URI는 다음과 같이 정의하였다:

 

 

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

[{EXPRESS_ROOT}/app.js]

1
2
3
4
5
6
7
8
9
10
11
12
13
var mongoose = require('mongoose');
 
...
 
//////////////////////////////////////////////////////
// ------- mongoose connections -------
 
mongoose.connect(uri, function(req, res) {
  console.log('mongodb users connected');
});
 
...

 

 

 

Part 3 - 간단한 mongoose 미들웨어 작성

Data Schema는 사용자의 ID, 이름, 패스워드로 구성하였으며, 다음과 같이 코드를 작성한다:

 

[{EXPRESS_ROOT}/routes/mongodb.js]

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
var mongoose = require('mongoose');
var myCount = 0;
 
// Users Schema
var UserSchema = mongoose.Schema({
   userId: String,
   userName: String,
   password: String
});
 
// compiles our schema into a model
var Users = mongoose.model('Users', UserSchema);
 
 
//////////////////////////////////////////////////////////////////////
// insert an user
exports.InsertUser = function(userId, userName, userPwd) {
 
    var myUser = new Users({
        userId: userId,
        userName: userName,
        password: userPwd
    });
 
    // save an user
    myUser.save(function(err) {
      console.log('A new user is inserted.');
      console.log('');
   });
 
};
 
 
//////////////////////////////////////////////////////////////////////
// remove the user
exports.RemoveUserById = function(userId) {
 
    // find the user
    Users.findOne({userId: userId}, function(err, data) {
 
        if(data != null) {
            console.log('The user is found.');
            console.log('');
 
            Users.remove({userId: userId}, function(err, data) {
                console.log('The user is removed.');
                console.log('');               
            });
 
        }
        else {
            console.log('Cannot find the user.');
            console.log('');
        }
 
    });
 
};
 
 
//////////////////////////////////////////////////////////////////////
// update the user
exports.UpdateUser = function(userId, newData) {
 
    // find the user
    Users.findOne({userId: userId}, function(err, data) {
 
        if(data != null) {
            console.log('The user is found.');
            console.log('');
 
            Users.update({userId: userId}, newData, function(err, data) {
                console.log('Successfully changed user account.');
                console.log('');               
            });
 
        }
        else {
            console.log('Cannot find the user.');
            console.log('');
        }
 
    });
 
};
 
 
//////////////////////////////////////////////////////////////////////
// user counts
exports.UserCounts = function() {
 
    Users.count({}, function(err, count) {
        console.log('count: ' + count);
        myCount = count;
    });
 
    return myCount;
 
};

 

User를 등록(insert), 삭제(remove) 및 정보를 업데이트(update)하는 함수로 구성하였다.

 

 

 

Part 4 - 테스트

간단한 테스트를 해보자. app.js에 다음 코드를 생성한다.

 

[{EXPRESS_ROOT}/app.js]

 

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
app.get('/insertuser', function(req, res, next) {
   mongodb.InsertUser('cinema4d', 'gchoi', '12345');
   res.send('success: the user inserted');
});
 
app.get('/removeuser', function(req, res, next) {
   mongodb.RemoveUserById('cinema4d');
   res.send('success: the user removed');
});
 
app.get('/updateuser', function(req, res, next) {
   var newData = {
      userId: 'c4d',
      userName: 'gulae',
      password: 'asdf'
   };
 
   mongodb.UpdateUser('cinema4d', newData);
   res.send('success: the user updated');
});
 
app.get('/usercount', function(req, res, next) {
   res.send('User counts: ' + mongodb.UserCounts());
});
 
...

 

 

웹브라우저 주소창에 다음을 각각 입력하고, MongoDB를 통해 데이터를 확인한다:

 

127.0.0.1/insertuser
 
127.0.0.1/removeuser
 
127.0.0.1/updateuser
 
127.0.0.1/usercount

 

[출처] https://cinema4dr12.tistory.com/836

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
공지 오라클 기본 샘플 데이터베이스 졸리운_곰 2014.01.02 86411
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 78845
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 95611
42 블록체인 기반 플랫폼 비즈니스를 이해하자 졸리운_곰 2017.09.10 1554
41 다운타임 없는 서비스 구현 패턴 file 졸리운_곰 2017.09.10 1232
40 테이블의 수직분할과 수평분할에 대한 이해 file 졸리운_곰 2017.09.10 3910
39 정규화와 응집도에 대한 고찰 file 졸리운_곰 2017.05.28 1785
38 머신러닝 새 도전…“클라우드를 벗어나라" file 졸리운_곰 2017.05.28 1711
37 보안성 높이는 공공 거래장부 블록체인 file 졸리운_곰 2017.05.28 1759
36 디지털, 속도의 전쟁 VS 데이터, 품질의 전쟁 file 졸리운_곰 2017.05.05 1516
35 04. 데이터 모델링의 3단계 진행 file 졸리운_곰 2016.03.15 1659
34 데이터베이스 설계의 기본 원리.pdf file 졸리운_곰 2016.03.15 2354
33 실체유형(Entity Type) 정의 사항 및 도출 file 졸리운_곰 2015.05.21 2199
32 마농의 SQL 백문백답: 단순하고 쉽게 작성하는 SQL 노하우 [1회] file 졸리운_곰 2015.05.21 1830
31 sql개발자-sql전문가자격시험 시험 예제.pdf file 졸리운_곰 2015.02.15 2303
30 데이터베이스 선정에는 비밀이 있다 - 4부 졸리운_곰 2015.01.15 2100
29 데이터베이스 선정에는 비밀이 있다 - 3부 졸리운_곰 2015.01.15 2044
28 데이터베이스 선정에는 비밀이 있다 - 2부 졸리운_곰 2015.01.15 1828
27 데이터베이스 선정에는 비밀이 있다 - 1부 졸리운_곰 2015.01.15 2393
26 지금 우리에게 필요한 것은 데이터베이스 성능 최적화이다 (2부) 졸리운_곰 2015.01.15 1489
25 우리에게 필요한 것은 데이터베이스 성능 (1부) 졸리운_곰 2015.01.15 1784
24 21회 결과 secret 졸리운_곰 2014.11.10 0
23 [데이터아키텍쳐준전문가] 시험 fail 자료 secret 졸리운_곰 2014.08.31 0
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED