koa2 mysql增删改查_koa2对mongodb的增删改查

构建项目

npm install -g koa-generator

koa2 -e projectname

npm install mongoose

说明:我们用mongoose来操作mongodb,需要安装mongoose。生成项目后,在项目里新建一个文件夹dbs,用来存放和数据库相关的配置文件,配置文件config.js声明数据库的配置选项,里面再创建一个models文件夹,存放模型文件,目录结构如下

6273428d6c29

image.png

config.js

module.exports = {

dbs:'mongodb://127.0.0.1:27017/dbs'

}

说明:在mongodb中创建一个数据库,为dbs

person.js

const mongoose = require('mongoose')

let personSchma = new mongoose.Schema({

name:String,

age:Number

})

module.exports = mongoose.model('Person',personSchma)

说明:利用mongoose操作mongodb,需要引入这个模块。首先我们要用mongoose提供的schema方法声明一个模式,也就是描述存放的数据的字段和字段类型,接着再通过这个模式创建一个模型,这个模型封装了一些操作数据库的方法,我们需要把模型导出来供我们使用。

app.js

const Koa = require('koa')

const app = new Koa()

const views = require('koa-views')

const json = require('koa-json')

const onerror = require('koa-onerror')

const bodyparser = require('koa-bodyparser')

const logger = require('koa-logger')

//操作数据库我们需要这样,引入这两个模块哦

const mongoose = require('mongoose')

const dbConfig = require('./dbs/config')

const index = require('./routes/index')

const users = require('./routes/users')

// error handler

onerror(app)

// middlewares

app.use(bodyparser({

enableTypes:['json', 'form', 'text']

}))

app.use(json())

app.use(logger())

app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {

extension: 'ejs'

}))

// logger

app.use(async (ctx, next) => {

const start = new Date()

await next()

const ms = new Date() - start

console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)

})

// routes

app.use(index.routes(), index.allowedMethods())

app.use(users.routes(), users.allowedMethods())

//mongoose

mongoose.connect(dbConfig.dbs,{

useNewUrlParser:true

})

// error-handling

app.on('error', (err, ctx) => {

console.error('server error', err, ctx)

});

module.exports = app

添加的代码是

const mongoose = require('mongoose')

const dbConfig = require('./dbs/config')

//mongoose

mongoose.connect(dbConfig.dbs,{

useNewUrlParser:true

})

说明:在app.js中引入mongoose和数据库的配置文件config.js,然后连接dbs数据库,传递进去的参数就是config.js文件里的dbs的值。

到这里,我们就连接上数据库了,接下来,就编写接口操作数据库。

编写增删改查数据的接口

在router文件夹下的user.js中编写接口

const router = require('koa-router')()

//要操作数据库了,之前我们在models里面根据描述创建了模型

//现在根据模型我们实例化一个表出来

//那我们需要在这个接口文件中,引进我们创建的模型,就是person文件啦

//再说一遍,schema描述表的字段,moudle里面有增删改查的操作

const Person = require('../dbs/models/person')

router.prefix('/users')

router.get('/', function (ctx, next) {

ctx.body = 'this is a users response!'

})

router.get('/bar', function (ctx, next) {

ctx.body = 'this is a users/bar response'

})

//新建一个用来操作数据库的接口

router.post('/addPerson',async function(ctx){

//创建这个模型的实例啦

const person = new Person({

//通过post请求得到的body里的数据,添加到数据库

name: ctx.request.body.name,

age: ctx.request.body.age

})

// //保存这条数据哦

// await person.save()

// //返回这个操作的状态看看,不能总是0

// ctx.body = {

// code:0

// }

//换一种写法,我们需要捕获一下异常

let code

try {

//save方法是模型封装好的,实例可以调用这个方法

await person.save()

code = 0

} catch (error) {

code = -1

}

ctx.body = {

code:code

}

})

router.post('/getPerson',async function(ctx) {

const result = await Person.findOne({name:ctx.request.body.name})

const results = await Person.find({name:ctx.request.body.name})

ctx.body = {

code:0,

result,

results

}

})

router.post('/updatePerson',async function(ctx) {

const result = await Person.where({

name:ctx.request.body.name

}).update({

age:ctx.request.body.age

})

ctx.body = {

code:0

}

})

router.post('/removePerson',async function(ctx) {

const result = await Person.where({

name:ctx.request.body.name

}).remove()

ctx.body = {

code:0

}

})

module.exports = router

测试方法:安装postman,填写我们接口的地址,根据情况选择请求方式,这里是post,还要注意的一点是,user.js里的接口还有一个前缀,也就是文件中的router.prefix('/users'),它的前缀就是/users。

测试getPerson的接口如下

6273428d6c29

image.png

数据库如下

6273428d6c29

image.png

总结:

mudels下的person.js对应的就是我们建的表,我们是通过mongoose操作数据库的,并不是mongodb原生的api,因此我们要引入这个mongoose。接着,通过mongodb提供的schema创建一个描述,是描述这个数据表的,这样,数据表就有字段了。但还不能操作它,现在我们需要通过这个描述,创建一个模型,模型里面有封装好的操作数据库的一些方法。model在这里就相当于一个桥梁,它既关联着数据表的描述,又关联着数据库。最终要完成实际操作的,还是要由实例来完成。因此,在我们编写接口的文件中,引入mongoose和模型,并且通过模型创建一个实例出来,就可以在接口操作数据啦。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值