笔者的前端开发已经有些时日了,对于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以及其生态,提高本身的知识储备跟笔者一块儿加油!