[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 86127
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 78631
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 95351
16 [ADsP] 취업 깡패 ADP 뿌시기! "빅데이터 분석가 최고의 자격증이에요" file 졸리운_곰 2022.11.20 1538
15 ADsP Chap01.Chap02 file 졸리운_곰 2018.01.01 1904
14 [ADsP준비] chap04.데이터마트 file 졸리운_곰 2018.01.01 1147
13 [ADsP준비] chap03.데이터분석 개요 file 졸리운_곰 2018.01.01 1925
12 [ADsP준비] chap02. 데이터의 이해 file 졸리운_곰 2018.01.01 1542
11 [ADsP준비] chap01.데이터의 이해 file 졸리운_곰 2018.01.01 1637
10 [ADsP] 제12회 데이터분석준전문가 시험 복원 file 졸리운_곰 2017.11.23 2094
9 [빅데이터자격증] 제3회 데이터분석 준전문가(ADsP) 시험 후기 기출문제 정리 file 졸리운_곰 2017.11.19 1945
8 [시험후기] 제 11회 ADsP 시험 후기 & 기출문제 복원 file 졸리운_곰 2017.11.19 1818
7 [ADsP] 제12회 데이터분석준전문가 시험 복원 file 졸리운_곰 2017.11.05 4994
6 제 9회 ADsP - 시험 후기 file 졸리운_곰 2017.05.03 1663
5 ADSP요약정리.pdf file 졸리운_곰 2016.10.23 8199
4 [빅데이터자격증] 제3회 데이터분석 준전문가(ADsP) 시험 후기 기출문제 정리 file 졸리운_곰 2016.10.23 3169
3 R 기본 문법 및 통계 프로그래밍 file 졸리운_곰 2014.10.24 3342
2 R을 이용한 데이터 분석 실무.pdf file 졸리운_곰 2014.10.24 3569
1 R 기초입문 - XMLArchive file 졸리운_곰 2014.10.24 1657
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED