2016年7月3日 星期日

Node.js筆記:Blog system(3)

新增資料庫功能

先在專案中新增一個”lib”的資料夾, 並新建一個檔案”db.js”. 在這裡我們要使用mongoose來存取MongoDB.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var Blog = new Schema({
    Username: String,
    Article: String,
    CreateDate: Date
});

var Comment = new Schema({
    Visitor: String,
    Comment: String,
    MessageID: Schema.Types.ObjectId,
    CreateDate: Date
});

mongoose.model( 'Blog', Blog );
mongoose.model( 'Comment', Comment );
mongoose.connect('mongodb://localhost/blog');

在上面我們新增的兩個model, 一個叫Blog, 一個是Comment. 最後一行則是連線到本機端的MongoDB伺服器.

接著修改apis.js初始化資料庫
主要是利用require把資料庫設定載入, 再把定義好的model也加入.

require('../lib/db');

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Blog = mongoose.model('Blog');
var Comment = mongoose.model('Comment');

...

支線任務:
1.brew update error.
問題簡述在此:https://github.com/Homebrew/legacy-homebrew/issues/49879
解決方式就是利用下面兩組command就可以讓brew正常運作.

    $sudo chown -R $(whoami):admin /usr/local
    $cd $(brew --prefix) && git fetch origin && git reset --hard origin/master

2.MongoDB使用.
安裝:

//Step 1 - Installation ( Don't follow this step if you have already installed MongoDB ):
brew update
brew install mongodb

//Step 2 - Run Mongo Daemon:
mkdir -p /data/db
sudo mongod

//Step 3 - Run Mongo Shell Interface:
mongo

新增功能

1.首頁列出所有文章
修改routes/index.js阿

利用find()找出資料庫中所有的資料, 並把資料存在blogs物件中, 最後把blogs物件回傳給頁面.

require('../lib/db');

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Blog = mongoose.model('Blog');

router.get('/', function(req, res, next) {
    res.locals.username = req.session.name ;
    res.locals.authenticated = req.session.logined;
    Blog.find(function (err, blogs, count) {
      res.render('index', {
        title : 'Blog System';
        blogs : blogs;
      });
    });
});

module.exports = router;

修改index.jade, 利用forloop把blogs物件的資料都列印在頁面上.

...
div(style='padding:50px;')
        h1= title

        for article in blogs
                div
                    div(style='float:left;margin-top:10px;')= article.Username
                    div(style='float:right;margin-top:10px;')= article.CreateDate
                    br
                    div(style='clear:both')= article.Article
                        a(href='/users/message/'+article.id, style='float:right;margin-top:105px;margin-right:20px;') Leave a message
                    hr(style='margin-top:110px;')

2.新增文章
views/users/add_article.jade

doctype html
html
    head
        title= Login
    body
        div(style='float:left;margin:10px;')
            a(href='/') Home

        div(style='float:right')
            if (username && authenticated)
                span #{username}
                a(href='/users/profile', style='margin:10px;') Profile
                a(href='/users/signout', style='margin:10px;') Sign Out
            else
                a(href='/users/signin', style='margin:10px;') Log In
                a(href='/users/register', style='margin:10px;') Register
                a(href='/users/forget', style='margin:10px;') Forgot password

        div(style='padding:50px;')
            form(name="add", action="/apis/add", method="post")
                h1 Add Article
                div
                    p
                        span Writer:
                        label(style='padding-right:50px') #{username}
                    p
                        textarea(cols="50", rows="25", style='resize : none;', name="Content")
                    div
                        span(style='padding-right:377px')
                        input(type="submit", name="submit", value="Save")

後半段為一個POST方法, 當按下送出按鈕後會執行 /apis/add 的網址.

修改users.js跟apis.js
下面先判斷使用者是否有登入, 如果有登入才能進入新增文章.

#/users/js

router.get('/add_article', function(req, res, next) {
  if((!req.session.name) || (!req.session.logined)) {
    res.redirect('/');
    return;
  }
  res.locals.username = req.session.name;
  res.locals.authenticated = req.session.logined;
  res.render('users/add_article');
});

...
#/apis.js

router.post('/add', function(req, res, next) {
  if (!req.session.name) {
      res.redirect('/');
      return;
  }
  new Blog({
      Username: req.session.name,
      Article: req.body.Content,
      CreateDate: Date.now()
  }).save( function( err ){
      if (err) {
          console.log('Fail to save to DB.');
          return;
      }
      console.log('Save to DB.');
  });
  res.redirect('/');
});

enter image description here

沒有留言:

張貼留言