본문 바로가기
  • Let's go grab a data
Development/NodeJS

ejs 활용, mongoose 데이터 연동, simple counter 구현

by pub-lican-ai 2017. 1. 25.
반응형

ejs 활용, mongoose 데이터 연동, simple counter 구현   #ejs #mongoose #mongoDB #simplecounter


ejs : Embedded Javascript


[ejs 설치]

1. 윈도우 탐색기 프로젝트 폴더에서 cmd 또는 git bash를 열어서

$npm install ejs --save


2. node_modules\ejs에 설치됨


[ejs로 hello world]

1. Atom의 프로젝트 폴더에서 views 폴더 생성


2. views 폴더 내에 testejs.ejs 파일 생성


3. 생성된 testejs.ejs 파일내에서 html 타이핑 후 tab을 눌러 HTML 기본 태그 호출하기 또는 아래 내용 입력

<!DOCTYPE html>

<html>

  <head>

    <meta charset="utf-8">

    <title>Test EJS page</title>

  </head>

  <body>

Hello EJS

  </body>

</html>


4. public 폴더 내의 index.html 파일은 삭제


5. app.js(또는 기입력한 index.js)에 아래와 같이 입력함

app.set("view engine",'ejs');

app.get('/',function(req,res) {

  res.render('testejs',data);

});


6. cmd 또는 git bash에서 nodemon 명령어를 통해 서버 실행


7. http://localhost:3000 에서 ejs 뷰 (Hello ejs) 확인



[간단한 counter 만들기]

1. app.js 파일내에 변수 추가하기

var data = {count:0};


2. app.js(index.js)에서 아래와 같이 수정함

app.get('/',function(req,res) {

  data.count++;

  res.render('testejs',data);

});


3. testejs.ejs에서 아래와 같이 추가함

<!DOCTYPE html>

<html>

  <head>

    <meta charset="utf-8">

    <title>Test EJS page</title>

  </head>

  <body>

    <h2>Hello ejs</h2>

    <br>

    view counter from local: <%= count %>

  </body>

</html>


4. http://localhost:3000/를 계속 호출하여 count 증가하는지 확인


[mongoose설치]

1. 윈도우 탐색기 프로젝트 폴더에서 cmd 또는 git bash를 열어서

$npm install mongoose --save


2. node_modules\mongoose에 설치됨


[mongoDB에 연결]

1. 아래 링크 참고하여 mongoDB 로컬 설치 후 mongod로 DB 서비스 실행, test 데이터베이스 생성

http://pubdata.tistory.com/80 


2. app.js(index.js)에 아래 코드 삽입

var mongoose = require('mongoose');

mongoose.connect("mongodb://localhost:27017/test");

var db = mongoose.connection;


db.once("open",function() {

  console.log("DB connected!!");

});

db.on("error",function(err) {

  console.log("DB Error:", err);

});


3. 서버를 재시작해서 console에 DB connected!!가 나타나면 성공


[mongoDB 데이터 연동으로 counter 구현]

1. app.js(index.js)에 아래 코드 삽입으로 스키마와  모델 생성

var dataSchema = mongoose.Schema({

  name:String,

  count:Number

});


var Data = mongoose.model('data',dataSchema);

Data.findOne({name:"myData"},function(err,data) {

  if(err) return console.log("db error:",err);

  if(!data){

    Data.create({name:"myData",count:0},function(err,data) {

      if(err) return console.log("db creeate err:",err);

      console.log("Counter DB created!:",data);

    });

  }

});


2. nodemon이 떠있는 console에 Counter DB created!!가 최초 1회 나오면 모델 생성 성공


3. app.js(index.js)에 내용 수정

//data = {count:0}

app.get('/',function(req,res) {

 //data.count++;

 //res.render('testejs',data);

  addCounter(res);

});

function addCounter(res) {

  Data.findOne({name:"myData"},function(err,data){

    if(err) return console.log("Data error:",err);

    data.count++;

    data.save(function(err) {

      if(err) return console.log("Data error:",err);

        res.render('testejs',data);

    });

  });

}


4. http://localhost:3000 를 여러번 호출하여 count 증가확인

   mongoDB열어서 test 데이터베이스의 datas 컬렉션의 'myData'이름을 가진 오브젝트의 count가 증가하는지 확인


[reset/get/set 추가하기]

1. app.js(index.js)dp 내용 추가

app.get('/reset',function(req,res) {

  setCounter(res,0);

});


app.get('/set/count',function(req,res) {

  if(req.query.count) setCounter(res,req.query.count);

  else getCounter(res);

});


app.get('/set/:num',function(req,res) {

  if(req.params.num) setCounter(res,req.params.num);

  else getCounter(res);

});


function setCounter(res, num) {

  Data.findOne({name:"myData"},function(err,data){

    if(err) return console.log("Data error:",err);

    data.count = num;

    data.save(function(err) {

      if(err) return console.log("Data error:",err);

        res.render('testejs',data);

    });

  });

}


function getCounter(res){

  Data.findOne({name:"myData"},function(err,data){

    if(err) return console.log("Data error:",err);

      res.render('testejs',data);

  });

}


2. 각각 호출하여 확인

 http://lcoalhost:3000/reset

 http://localhost:3000/count?count=5

 http://localhost:3000/5



일부 내용 출처: 

http://blog.naver.com/azure0777/220475344428

http://blog.naver.com/azure0777/220482056110

http://blog.naver.com/azure0777/220488363644


반응형