koa2|koa2 mysql增删改查_手把手教你基于koa2,mongoose实现增删改查

#####初始化项目
npm init -y
先安装一波乱七八糟的依赖插件(需要具备一定的koa2知识,至于mongoDB自行百度安装教程),模板引擎我使用的是art-template(据说是性能最好的,而且是因为JQ时代的产物,念旧)
npm i koa koa-router koa-bodyparser koa-static koa-views art-template koa-art-template mongoose -S
#####安装nodemon实时监听修改
npm i nodemon -D
新建app.js入口文件,撸一把基础代码
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const bodyParser = require('koa-bodyparser')
// const Router = require('koa-router')
const path = require('path')
// const router = new Router()
const {connect} = require('./dbs/init.js') //导入mongodb数据库
const {createUser} = require('./controller/users.js')
// 模板引擎
const render = require('koa-art-template');
render(app, {
root: path.join(__dirname, 'views'),
extname: '.html',
debug: process.env.NODE_ENV !== 'production'
});
//自执行函数,链接数据库
; (async ()=>{
await connect()
})()
const userRouter = require('./controller/users.js')
app.use(userRouter.routes(),userRouter.allowedMethods())
// app.use(router.routes(),router.allowedMethods())
app
.use(bodyParser({enableTypes:['json', 'form', 'text']}))
.use(require('koa-static')(__dirname + '/public'))
.use(views(__dirname + '/views', {
extension: 'html'
}))
app.listen(4000,()=>{
console.log('listen at port localhost:4000 ');
})
新建dbs文件夹,在下面统一管理数据库相关,新建init.js数据库初始化
const mongoose = require('mongoose')
const db = 'mongodb://localhost/mongo_test'; //link
// const glob = require('glob')
// const {resolve} = require('path')
// exports.initSchemas = ()=>{
// // glob.sync(resolve(__dirname,'./schema','**/*.js')).forEach(require)
// }
// 连接数据库,URL以mongodb:// + [用户名:密码@] +数据库地址[:端口] + 数据库名。(默认端口27017)
// 连接mongodb数据库的链接解析器会在未来移除,要使用新的解析器,通过配置{ useNewUrlParser:true }来连接 ;其他警告参考:https://mongoosejs.com/docs/deprecations.html
/**
* mongoose从@5.2.8后会弃用一些指令,为防止程序如下警告:
* (node:24864) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
* (node:24841) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
* 可以如下设置
*/
mongoose.set('useNewUrlParser', true)
mongoose.set('useFindAndModify', false)
mongoose.set('useCreateIndex', true)
let dbc = mongoose.connection
exports.connect = ()=> {
// 链接数据库
mongoose.connect(db)
let maxConnectTimes = 0
return new Promise((resolve,reject)=>{
// 增加数据库监听事件:断开链接
dbc.on('disconnected',()=>{
console.log('***********数据库断开***********')
if(maxConnectTimes<=3){
maxConnectTimes++
mongoose.connect(db)
}
else {
reject()
throw new Error('数据库出现问题,请人为修理.....')
}
})
dbc.on('error',err=>{
console.log('***********数据库出错***********')
if(maxConnectTimes<=3){
maxConnectTimes++
mongoose.connect(db)
}
else {
reject()
throw new Error('数据库出现问题,请人为修理.....')
}
})
dbc.once('open',()=>{
console.log('MongoDB Connected successfully!')
resolve()
})
})
}
在dbs文件夹下新建schema文件夹用于创建各种schema表,新建Users.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let ObjectId = Schema.Types.ObjectId;
const userSchema = new Schema({
UserId : {type:ObjectId},
userName:{unique:true,type:String},//unique表示索引唯一
password:String,
gender:Number,
userStatus:Number,
createAt:{type:Date,default:Date.now()},
lastLoginAt:{type:Date,default:Date.now()}
},{collection:'users'})
const model = {
Users:mongoose.model('Users',userSchema)
}
// 发布模型
module.exports = model
新建controller文件夹,主要是用来处理一些业务逻辑,新建users.js文件
let {
addUser,
updateUser,
delUser,
findAllUsers,
findOne
} = require('./tools.js');
const common = require("../libs/common");
const Users = require('../dbs/schema/Users.js').Users
const Router = require('koa-router') ;
let router = new Router()
router.prefix('/user')
// 查找列表
router.get('/list',async (ctx)=>{
let code = 0 // 状态码
let msg = '' // 返回内容
let {keyword} = ctx.query ;
let params = {
keyword
}
let ret = await findAllUsers(params)
ctx.body = {
code,
list:ret,
msg:'操作成功'
}
})
// 查找信息
router.get('/detail',async (ctx)=>{
let code = 0 // 状态码
let msg = '' // 返回内容
let {id} = ctx.query ;
let params = {
id
}
let ret = await findOne(params)
ctx.body = {
code,
【koa2|koa2 mysql增删改查_手把手教你基于koa2,mongoose实现增删改查】list:ret,
msg:'操作成功'
}
})
router.post('/addUser',async (ctx)=>{
let code = 0 // 状态码
let msg = '' // 返回内容
let {userName,password,gender,type,id} = ctx.request.body ;
if(type=='edit'){
if(id){
let ret = await updateUser(ctx.request.body)
if(ret.ok==1){
code = 0
msg = '修改成功'
}
else {
code = -1
msg = '修改失败,'
}
}
else{
code = -1
msg = '参数错误,'
}
}
// 删除
else {
// let id = common.uuid();
let user = new Users({
userName,
password,
gender,
userStatus:1
})
try {
let ret = await addUser(user)
console.log(ret);
code = 0
msg = '添加成功'
} catch (error) {
code = -1
msg = '新建失败'
}
}
ctx.body = {
code,
msg
}
})
router.post('/del',async (ctx)=>{
let code = 0 // 状态码
let msg = '' // 返回内容
let ret = await delUser(ctx.request.body)
console.log(ret);
if(ret){
ctx.body = {
code,
msg:'删除成功'
}
}
else {
ctx.body = {
code:-1,
msg:'参数错误'
}
}
})
module.exports = router
在当前controller目录下新建增删改查工具方法,tools.js
// 导入schama
const Users = require('../dbs/schema/Users.js').Users
/* 查所有用户 */
exports.findAllUsers = async (params) => {
let keyword = params.keyword ||'' ;
const reg = new RegExp(keyword, 'i') //不区分大小写
// 模糊查询
let _filter = {
userStatus:1,
$or:[
{
userName:{$regex :reg}
}
]
}
let count = 0
count = await Users.countDocuments(_filter)
let ret = await Users.find(_filter).limit(20)
let _list = ret.map(v=>{
return {
username:v.userName,
gender:v.gender,
createAt:v.createAt,
lastLoginAt:v.lastLoginAt,
}
})
return {
count,
list:_list
}
};
/* 查单个用户 */
exports.findOne = async (params) => {
let ret = await Users.findOne({_id:params.id})
let info = {
id:ret._id,
userName:ret.userName,
createAt:ret.createAt,
lastLoginAt:ret.lastLoginAt,
gender:ret.gender
}
return {
info
}
};
/* 新增用户 */
exports.addUser = async (userParams) => {
console.log('add=');
console.log(userParams);
return await userParams.save();
};
/**
* 编辑
*/
exports.updateUser = async (userParams)=>{
console.log('edit=');
console.log(userParams);
return await Users.updateOne({_id:userParams.id},{
$set:{
userName:userParams.userName,
password:userParams.password,
gender:userParams.gender
}
})
}
/**
* 硬删除
*/
exports.removeUser = async (userParams)=>{
return await Users.findOneAndRemove({_id:userParams.id})
}
/**
* 软删除
*/
exports.delUser = async (userParams)=>{
return await Users.findOneAndUpdate({_id:userParams.id},{userStatus:0})
}
运行代码:配置package.json,scripts新增"dev": "nodemon node ./app.js"
运行:npm run dev
loacahost:4000/user/list获取列表
loacahost:4000/user/detail获取用户详情
loacahost:4000/user/addUser新增用户
loacahost:4000/user/del删除用户

    推荐阅读