koa2 mysql增删改查_koa2对mongodb的增删改查
構建項目
npm install -g koa-generator
koa2 -e projectname
npm install mongoose
說明:我們用mongoose來操作mongodb,需要安裝mongoose。生成項目后,在項目里新建一個文件夾dbs,用來存放和數據庫相關的配置文件,配置文件config.js聲明數據庫的配置選項,里面再創建一個models文件夾,存放模型文件,目錄結構如下
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的接口如下
image.png
數據庫如下
image.png
總結:
mudels下的person.js對應的就是我們建的表,我們是通過mongoose操作數據庫的,并不是mongodb原生的api,因此我們要引入這個mongoose。接著,通過mongodb提供的schema創建一個描述,是描述這個數據表的,這樣,數據表就有字段了。但還不能操作它,現在我們需要通過這個描述,創建一個模型,模型里面有封裝好的操作數據庫的一些方法。model在這里就相當于一個橋梁,它既關聯著數據表的描述,又關聯著數據庫。最終要完成實際操作的,還是要由實例來完成。因此,在我們編寫接口的文件中,引入mongoose和模型,并且通過模型創建一個實例出來,就可以在接口操作數據啦。
總結
以上是生活随笔為你收集整理的koa2 mysql增删改查_koa2对mongodb的增删改查的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 哈工大理论力学第八版电子版_校史上的这些
- 下一篇: 主板没有rgb接口怎么接灯_纯白信仰打造