1. 程式人生 > >nodejs web應用伺服器搭建(三):業務的實現+mongo的基礎使用

nodejs web應用伺服器搭建(三):業務的實現+mongo的基礎使用

前言

本章節主要是關注業務實現的,就是持久層資料的CURD操作,和業務處理。
資料:
mongoose 文件
其他章節連結:

nodejs web應用伺服器搭建(一):跑起你的伺服器
nodejs web應用伺服器搭建(二):express 框架說明(應用)
nodejs web應用伺服器搭建(三):業務的實現+mongo的基礎使用
nodejs web應用伺服器搭建(四):生產環境的搭建

介紹mongoDB

簡介

mongoDB屬於noSQL型(即非關係型的資料庫)資料庫,而mongoDB屬於文件型別,使用的簡易程度遠超於傳統資料庫,所以前端轉後端時可以以noSQL型別作為切入點,但傳統資料庫還是擁有非常大的優勢的,技術選型還是需要根據具體業務來決定,畢竟 技術脫離業務 就一文不值了

。接下來不過多介紹了,進入正題。

mongodb 的安裝使用。

首先先去mongoDB 官網,根據你的系統下載安裝程式 傳送門

1. 選擇自定義安裝

2.選擇你需要安裝的目錄

安裝完以後可以先檢視一下環境變數,win + R ,輸入CMD,命令列模式輸入 path,確定是否存在 %你的mongoDB安裝路徑%/bin 改 地址,如果沒有請在環境變數自行新增

3.建立你的資料目錄
你可以在任意目錄下建立你的資料目錄,如 c:\data\db

4. 啟動你的mongoDB
可以在命令臺輸入 mongod –port 10086 –dbpath 你的資料目錄(如上述:c:\data\db)
如果出現下面資訊,那就已經可以正常使用mongoDB了

2018-02-17T16:41:46.651+0800 I CONTROL  [initandlisten] MongoDB starting : pid=13264 port=10086 dbpath=C:\data\db 64-bit host=surface-book
2018-02-17T16:41:46.652+0800 I CONTROL  [initandlisten] targetMinOS: Windows Vista/Windows Server 2008
2018-02-17T16:41:46.653+0800 I CONTROL  [initandlisten] db version v3.2.10
2018
-02-17T16:41:46.653+0800 I CONTROL [initandlisten] git version: 79d9b3ab5ce20f51c272b4411202710a082d0317 2018-02-17T16:41:46.653+0800 I CONTROL [initandlisten] allocator: tcmalloc 2018-02-17T16:41:46.654+0800 I CONTROL [initandlisten] modules: none 2018-02-17T16:41:46.654+0800 I CONTROL [initandlisten] build environment: 2018-02-17T16:41:46.657+0800 I CONTROL [initandlisten] distarch: x86_64 2018-02-17T16:41:46.658+0800 I CONTROL [initandlisten] target_arch: x86_64 2018-02-17T16:41:46.659+0800 I CONTROL [initandlisten] options: { net: { port: 10086 }, storage: { dbPath: "C:\data\db" } } 2018-02-17T16:41:46.662+0800 I STORAGE [initandlisten] wiredtiger_open config: create,cache_size=4G,session_max=20000,eviction=(threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),checkpoint=(wait=60,log_size=2GB),statistics_log=(wait=0), 2018-02-17T16:41:46.854+0800 I NETWORK [HostnameCanonicalizationWorker] Starting hostname canonicalization worker 2018-02-17T16:41:46.854+0800 I FTDC [initandlisten] Initializing full-time diagnostic data capture with directory 'C:/data/db/diagnostic.data' 2018-02-17T16:41:46.895+0800 I NETWORK [initandlisten] waiting for connections on port 10086

mongodb 的使用說明

你需要了解一下關於mongodb的操作,和資料庫術語/概念

SQL術語/概念 MongoDB術語/概念 解釋/說明
database database 資料庫
table collection 資料庫表/集合
row document 資料記錄行/文件
column field 資料欄位/域
index index 索引
table joins 表連線,MongoDB不支援
primary key primary key 主鍵,MongoDB自動將_id欄位設定為主鍵

你還需要了解資料庫操作

  • 建立資料庫
  • 刪除資料庫
  • 插入文件
  • 刪除文件
  • 更新文件
  • 條件操作
  • $type操作
  • limit ship操作
  • 排序
  • 索引

你可以訪問該網站查閱相關操作 如何使用 傳送門

關於mongoose

一個JavaScript 的 mongoose ORM 庫

mongoose 文件

express的業務中介軟體

mongo配置

通過 mongoose 連結mongoDB,每次呼叫modal都會建立連結

// ./modal/config.js
var mongoose = require('mongoose');//引入mongoose庫
mongoose.connect('mongodb://localhost:10086/logs');//mongodb連線地址,demo為資料庫名稱,預設mongodb連線不需要密碼
exports.mongoose = mongoose;//匯出mongoose物件

建立modal

基礎modal 模組

// ./modal/base.js
var mongodb = require('./config');//引入config中的mongodb物件
var mongoose = mongodb.mongoose;//獲取mongoose
var Schema = mongoose.Schema;//獲取Schema,以便快捷使用
var ObjectId = Schema.Types.ObjectId;//獲取ObjectId型別,以便快捷使用

exports.mongodb = mongodb;//匯出mongodb
exports.mongoose = mongoose; //匯出mongoose
exports.Schema = Schema;//匯出Schema
exports.ObjectId = ObjectId;//匯出ObjectId
exports.Mixed = Schema.Types.Mixed;//匯出Mixed

日誌modal

// ./modal/log.js
var base = require('./Base');
var ObjectId = base.ObjectId;
var logScheme =new base.Schema({
    host:{
        type:'String',
        required:true
    },
    path:{
        type:'String',
        required:true
    },
    msg:String,
    file:String,
    stack:String,
    userAgent:String,
    //date:String,
    createTime:{type:Date,default:Date.now}//建立時間
});
logScheme.index({createTime:1},{"background" : true});//設定索引
var logEntity = base.mongoose.model('logEntity',logScheme,'logs');//指定在資料庫中的collection名稱為user
exports.logEntity  = logEntity;//匯出實體

mongoose的應用

路由中介軟體,處理 /logs 請求,此api功能為,日誌記錄查詢

var express = require('express');

var fs = require('fs');
var router = express.Router();

var logEntity = require('../models/log').logEntity;
router.use('/logs', function(req, res, next) {
    var count_per_page = 50,
        page = 1,
        start,
        end;
    if(req.method == 'GET'){
        page = req.query.page || 1
        start = req.query.start || Date.now() - 7 * 24 * 3600 * 1000;
        end = req.query.end || Date.now();

    }else if (req.method == 'POST'){
        page = req.body.page || 1
        start = req.body.start || Date.now() - 7 * 24 * 3600 * 1000;
        end = req.body.end || Date.now();
    }
    res.header("Access-Control-Allow-Origin", "*");

    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header('Access-Control-Allow-Credentials','true');

    logEntity.find({ createTime:{ "$gte": new Date(start), "$lt":new Date(end)}}) // $條件查詢
        .select('-_id host file stack createTime msg userAgent path')
            if (!error) {
                throw new Error('error')
            }
            res.json(docs)
        })
});