筆者的前端開發已經有些時日了,對於node一直保留着最初的恐懼,假若一座不可跨越的高山,思前想後終於邁出最後一步,踏入了開拓本身視野的新視界,但願在看這篇文章的你能夠一塊兒跟我動手嘗試。
若是你是個急性子,我就提供一波傳送門 github:https://github.com/tenggouwa/...
你能夠先star,再拉代碼,慢慢的看這篇文章。前端
next generation web framework for node.js
面向node.js的下一代web框架。
由Express團隊打造,特色:優雅、簡潔、靈活、體積小。幾乎全部功能都須要經過中間件實現。node
nodegit
mongodbgithub
本地安裝nodemonweb
建立目錄mongodb
mkdir node-app && cd node-app
npm init
yarn add koa -S
touch app.js
在編輯器中打開app.js並輸入如下代碼數據庫
const Koa = require('koa'); const app = new Koa(); app.use(async ctx => { // ctx.body 即服務端響應的數據 await ctx.body = 'Hello world!!!'; }) // 監聽端口、啓動程序 app.listen(3000, err => { if (err) throw err; console.log('runing at 3000'); })
啓動app.jsnpm
node app
或 nodemon app
安裝koa-routerwindows
yarn add koa-router -S
const router = require('koa-router')() module.exports = (app) => { router.get( '/index', app.controller.home.index ) }
home.js輸入如下代碼跨域
module.exports = { index: async(ctx, next) => { console.log(ctx) // 輸出ctx 以查看內容 ctx.response.body = '<h1>HOME page index</h1>' }, }
node app
或 nodemon app
安裝koa-bodyparser
yarn add koa-bodyparser -S
router.js添加代碼
router.post( '/post', bodyParser(), app.controller.home.post ) // 重點在'post'後面的bodyParser()
home.js添加代碼
post: async(ctx, next) => { console.log(ctx.request.body) // 輸出ctx 以查看內容 },
koa2-cors安裝
yarn add koa2-cors -S
在app.js內添加以下代碼
const cors = require('koa2-cors') ....... // 其餘代碼 app.use(cors())
至此,咱們就擁有了一套簡單的koa項目,能夠進行先後臺交互,或者mock數據搭建
yarn add mongoose -S
建立models文件夾並在app.js添加以下代碼
const mongoose = require('mongoose') const path = require('path') const fs = require('fs') // 連接數據庫必定放在koa前面 mongoose.Promise = require('bluebird') mongoose.connect('mongodb://127.0.0.1/tenggouwa',{useNewUrlParser: true}) // 獲取數據庫表對應的js對象所在的路徑 const models_path = path.join(__dirname, './models') // 已遞歸的形式,讀取models文件夾下的js模型文件,並require var walk = function(modelPath) { fs .readdirSync(modelPath) .forEach(function(file) { var filePath = path.join(modelPath, '/' + file) var stat = fs.statSync(filePath) if (stat.isFile()) { if (/(.*)\.(js|coffee)/.test(file)) { require(filePath) } } else if (stat.isDirectory()) { walk(filePath) } }) } walk(models_path)
在models裏建立block.js並加入以下代碼
'use strict' var mongoose = require('mongoose') var Schema = mongoose.Schema; /** * 定義一個模式(至關於傳統意義的表結構) * 每一個模式映射mongoDB的一個集合, * 它定義(只是定義,不是實現)這個集合裏面文檔的結構,就是定義這個文檔有什麼字段,字段類型是什麼,字段默認值是什麼等。 * 除了定義結構外,還定義文檔的實例方法,靜態模型方法,複合索引,中間件等
*/ var BlockSchema = new Schema({ peers: String, blocks: String, createAt: { type: Date, default: Date.now() }, updateAt: { type: Date, dafault: Date.now() } }) /** * 定義模型 * 模型用來實現咱們定義的模式,調用mongoose.model來編譯Schema獲得Model * @type {[type]} */ // 參數User 數據庫中的集合名稱, 不存在會建立. // console.log(BlockSchema) var Block = mongoose.model('Block', BlockSchema) module.exports = Block ```
接下來咱們就能夠在controller裏面去操縱mongodb,進行業務操做了。例如:
delBlock: async(ctx, next) => { const params = ctx.request.body // 拿到返回的參數 const result = await Block.where({ // 經過id去Block裏面查找對應數據 _id: params.id }).remove() // 將該條數據刪除 },
save()
find()
finOne()
where()
where().update()
where().remove()
find().sort()
find().sort().skip(頁碼).limit(單頁數據)
當你看完這篇文章,你已經明白基本的koa+mongdb的用法了,但願你能夠經過學習node以及其生態,提高本身的知識儲備跟筆者一塊兒加油!