IBM Cloud 서비스 |
IBM Cloud를 이용해서 MongoDB를 올리는 기초적인 내용입니다.
우선 bluemix를 이용할 것이고 학생이나 학부등, 학교에 소속되어 있는 사람들은 다양하게 지원을 받을 수 있습니다.
그것 또한 알아보시면 좋겠습니다.
구글에 검색해서 들어갑니다.
메인화면 |
회원가입을 하고 나면 대쉬보드에 아무것도 없을 것 입니다.
우측 상단의 리소스 작성을 눌러줍니다.
카탈로그 검색 |
카탈로그에 MongoDB를 검색해줍니다.
리소스 작성 |
리소스를 순서에 따라서 작성해줍니다.
서버 완료 |
그러면 해당 서비스를 올리는 프로그레스가 지나가게 될 것이고 정상적으로 실행 되었다면
해당 화면과 같이 나타나게 됩니다.
그러면 우선 서버에 몽고디비가 올라가 있다는 것을 의미하고 저희는 이 곳에 접속해야 하는데
그러기 위해서는 서비스 인임 정보를 획득해줘야 합니다.
서비스 신임 정보 획득 |
서비스 신임 정보에 처음에는 아무것도 없겠지만,
새 신임 정보를 눌러서 만들어 줍니다. 저는 위와 같이 무비크레딧이라는 신임 정보를 만들었습니다.
그렇게 되면 json을 확인할 수 있는데 이 json을 통해서 우리의 노드js에서 몽고디비를 접속할 수 있습니다.
서비스 신임 정보 작성 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | { "services": { "compose-for-mongodb": [ { "credentials": { "db_type": "ㄻㄴㅇㄻㄴㄹ", "maps": [], "instance_administration_api": { "instance_id": "ㅁㄴㅇㄻㅇㄴㄻㄴㅇㄹ", "root": "ㅁㄴㅇㄻㄴㅇㄹㄴㅁㅇㄹㄴㅇㅁㄹㄴㅇㅁ", "deployment_id": "ㅁㄴㅇㄹㄴㅁㅇㄹㄴㅇㅁㄹㄴㅇㅁㄹㄴㅇㅁㄹ" }, "name": "ㅇㅁㄴㄹㄴㅇㄹㄴㅇㅁㄹㄴㅇㅁㄹㄴㅇㅁㄹㄴㅇㅁㄹ", "uri_cli": "ㅁㄴㅇㅁㄴㅇㄹㄴㅁㄹㄴㅁㄻㄴㄹㄴㅇㅁㄹㄴㅁㅇㄹㄴㅇ", "deployment_id": "ㄴㅇㅁㄻㄴㄹㅇㄴㄹㄴㅁㅇㄹ", "uri": "ㅇㅁㄹㅇㄴㄹㄴㅁㄹㅇㄴㅁㄹㅇㄴㅁㄹㄴㅇㅁㄹㅇㄴㅁ" } } ] } } | cs |
저는 로컬 폴더에다 mongodb_credit.json을 만들어 줬습니다.
그리고 bluemix에서 제공해주는 sample파일을 활용해서 커넥터를 만들었습니다.
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 | var cfenv = require('cfenv'); var DBClient = require('mongodb').MongoClient; const util = require('util') const assert = require('assert'); var crdeditLocal; try { crdeditLocal = require('../config/mongodb_credit.json'); console.log("Loaded local VCAP"); } catch (e) { // console.log(e) } const appEnvOpts = crdeditLocal ? { vcap: crdeditLocal } : {} const appEnv = cfenv.getAppEnv(appEnvOpts); // Within the application environment (appenv) there's a services object let services = appEnv.services; // The services object is a map named by service so we extract the one for MongoDB let mongodb_services = services["compose-for-mongodb"]; // This check ensures there is a services for MongoDB databases assert(!util.isUndefined(mongodb_services), "App must be bound to compose-for-mongodb service"); // We now take the first bound MongoDB service and extract it's credentials object let credentials = mongodb_services[0].credentials; // We always want to make a validated TLS/SSL connection let options = { ssl: true, sslValidate: true, useNewUrlParser: true }; // If there is a certificate available, use that, otherwise assume Lets Encrypt certifications. if (credentials.hasOwnProperty("ca_certificate_base64")) { let ca = [new Buffer(credentials.ca_certificate_base64, 'base64')]; options.sslCA = ca; } // This is a global variable we'll use for handing the MongoDB client around let mongodb; // This is the MongoDB connection. From the application environment, we got the // credentials and the credentials contain a URI for the database. Here, we // connect to that URI, and also pass a number of SSL settings to the // call. Among those SSL settings is the SSL CA, into which we pass the array // wrapped and now decoded ca_certificate_base64, function insertDB(dbName,collectionName,myItem){ return new Promise(function(resolve, reject){ DBClient.connect(credentials.uri, options, function (err, database) { // Here we handle the async response. This is a simple example and // we're not going to inject the database connection into the // middleware, just save it in a global variable, as long as there // isn't an error. if (err) { console.log(err); resolve(400) } else { // Although we have a connection, it's to the "admin" database // of MongoDB deployment. In this example, we want the // "examples" database so what we do here is create that // connection using the current connection. database.db(dbName).collection(collectionName).insertOne(myItem, function(insertError,result){ if(insertError){ console.log(insertError) resolve(404); } else{ console.log(result) resolve(200); } }) } }); }) } function selectDB(tableName,documentName){ return new Promise(function(resolve, reject){ DBClient.connect(credentials.uri+"/"+tableName, options, function (err, db) { // Here we handle the async response. This is a simple example and // we're not going to inject the database connection into the // middleware, just save it in a global variable, as long as there // isn't an error. if (err) { console.log(err); } else { // Although we have a connection, it's to the "admin" database // of MongoDB deployment. In this example, we want the // "examples" database so what we do here is create that // connection using the current connection. mongodb = db; console.log("connected:"+db); resolve(mongodb); } }); }) } module.exports = { insertDB : insertDB, } | cs |
이렇게 커넥터를 생성해줬습니다.
많은 내용이 있지만 json을 가져와서 json을 파싱해서 credentials를 만들어주고 그것을 암호화 하고, require('mongodb').MongoClient를 이용해서 접속하고
데이터를 삽입 시에 해당 데이터를 보여주는 함수를 만든 내용입니다.
1 2 | const DBConnector = require('./routers/mongodb_connector.js') DBConnector.insertDB("TEST","TEST",{name:"TEST"}) | cs |
그리고 서버 쪽에서는 해당 라우터를 가져와서 위와 같이 쓸 수 있습니다.
몽고DB를 알고 있는 분들이 bluemix를 통해서 쉽게 쓸 수 있을 것 같아서 작성한 내용이고,
bluemix에도 샘플 파일이 있기 때문에 쉽게 따라할 수 있을 것 입니다.