[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 86113
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 78624
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 95338
46 [데이터분석 & 데이터 사이언스] 수많은 데이터 사이언티스트들이 직장을 떠나는 이유는 무엇인가? file 졸리운_곰 2025.03.09 901
45 [데이터분석][파이썬][python] 한글 글꼴 사용 (matplotlib) 졸리운_곰 2024.04.18 1360
44 [데이터분석 & 데이터 사이언스] 데이터에 관한 꼭 알아야 할 오해와 진실 12가지 졸리운_곰 2024.01.17 1315
43 [데이터분석][파이썬][python] Awesome Dash Awesome file 졸리운_곰 2021.07.10 2338
42 [데이터분석][파이썬][python] ???? Introducing Dash ???? file 졸리운_곰 2021.07.10 1606
41 [dataset] (한글) 욕설 감지 데이터셋 file 졸리운_곰 2021.05.12 1559
40 [데이터분석][python] Dash를 사용하는 초보자 및 기타 모든 사용자를위한 Python의 대시 보드 file 졸리운_곰 2021.04.14 1762
39 [데이터분석][python] Dash를 사용하는 초보자 및 기타 모든 사용자를위한 Python의 대시 보드 file 졸리운_곰 2021.04.14 1602
38 [데이터분석][데이터 사이언스][python][Dash] Python, Dash 및 Plotly를 사용하여 COVID-19 사례 데이터 시각화 file 졸리운_곰 2021.03.28 1501
37 [데이터분석][머신러닝] When not to use machine learning or AI Adventures in wishful thinking, nonstationarity, and pattern-finding / 기계 학습 또는 AI를 사용하지 않아야하는 경우 희망찬 사고, 비정상 성, 패턴 찾기의 모험 file 졸리운_곰 2021.03.28 21621
36 [MSA][머신러닝] 쿠버네티스 기반의 End2End 머신러닝 플랫폼 Kubeflow #1 - 소개 file 졸리운_곰 2021.03.21 1135
35 [데이터사이언스] 데이터 과학자를위한 3 가지 훌륭한 디자인 패턴, 3 Great Design Patterns for Data Scientists file 졸리운_곰 2021.03.04 779
34 [데이터분석] 시계열 데이터에 AI를 사용하는 이유는 무엇입니까? file 졸리운_곰 2021.02.28 1191
33 [데이터분석] AI 예측 및 이상 탐지를위한 시계열 데이터 전처리 file 졸리운_곰 2021.02.28 1031
32 [데이터분석] bitcoin analysis 비트 코인 시계열 데이터에 대한 AI 이상 탐지 file 졸리운_곰 2021.02.27 1588
31 [데이터분석 & 데이터 사이언스] How To Create a Data Science Portfolio Website file 졸리운_곰 2021.02.14 1823
30 [데이터수집4] 오픈 API 데이터 수집 (소셜미디어 데이터 수집) file 졸리운_곰 2020.06.12 1950
29 [데이터수집3] 관계형 데이터베이스 데이터 수집 file 졸리운_곰 2020.06.12 1317
28 [데이터수집2] 분산시스템 로그 수집 (빅데이터 수집) file 졸리운_곰 2020.06.12 1492
27 [데이터수집1] 웹 크롤링, 웹 스크래핑 file 졸리운_곰 2020.06.12 1804
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED