koa+mongoose实现简单增删改查接口的示例代码
程序员文章站
2022-06-24 13:12:35
配合上一篇文章的联系人应用(),实现配套的基于nodejs的后台增删改查接口
1. 所需工具
node.js
mongodb
2. 主要node模块...
配合上一篇文章的联系人应用(),实现配套的基于nodejs的后台增删改查接口
1. 所需工具
- node.js
- mongodb
2. 主要node模块
koa(,一个nodejs的开发框架),mongoose(,mongdb操作工具)
3. 目录结构
4. 启动mongodb
首先在mongodb安装盘的根目录下(这里假设是d盘)新建一个文件夹data,然后在mongodb的bin中打开终端,输入mongod --dbpath d:\data,这样mongodb的数据存放地点就配置好了。
然后双击bin中的mongo.exe,mongodb就启动完成了。
5. app.js
app.js为入口文件,功能是连接数据库,导入文件,引入koa组件,最后启动服务。
'use strict'; const fs = require('fs'); const path = require('path'); const mongoose = require('mongoose'); const db = 'mongodb://localhost/test'; /* 连接数据库 */ mongoose.promise = require('bluebird'); mongoose.connect(db, {usemongoclient: true}); /** * 获取数据库表对应的js对象所在的路径 * @type {[type]} */ const models_path = path.join(__dirname, '/app/models'); /** * 已递归的形式,读取models文件夹下的js模型文件,并require * @param {[type]} modelpath [description] * @return {[type]} [description] */ let walk = function (modelpath) { fs.readdirsync(modelpath).foreach(function (file) { let filepath = path.join(modelpath, '/' + file) let stat = fs.statsync(filepath) if (stat.isfile()) { if (/(.*)\.(js|coffee)/.test(file)) { require(filepath) } } else if (stat.isdirectory()) { walk(filepath) } }) }; walk(models_path); require('babel-register'); const koa = require('koa'); const logger = require('koa-logger'); const session = require('koa-session'); const bodyparser = require('koa-bodyparser'); const app = new koa(); app.use(logger()); app.use(session(app)); app.use(bodyparser()); /** * 使用路由转发请求 * @type {[type]} */ const router = require('./config/router')(); app.use(router.routes()); app.use(router.allowedmethods()); app.listen(3000); console.log('app started at port 3000...');
6. 路由配置
路由配置在config/router.js中进行。
const router = require('koa-router'); const user = require('../app/controllers/user'); module.exports = function () { let router = new router({ prefix: '/api' }); router.post('/test/user/users', user.users); router.post('/test/user/user', user.user); router.post('/test/user/add', user.adduser); router.post('/test/user/delete', user.deleteuser); return router };
post方法第一参数为路由地址,第二参数为路由地址对应的方法。
7. 表结构定义
表结构定义在app/models/user.js中。
let mongoose = require('mongoose'); let schema = mongoose.schema; // 定义表结构 let userschema = new schema({ name: { type: string, required: true }, sex: string, area: string, always: boolean, relationship: array, mobile: string, phone: string, desc: string, id: string }); // 参数user 数据库中的集合名称, 不存在会创建. let user = mongoose.model('user', userschema); module.exports = user;
8. 工具方法
一些增删改查的工具方法放在app/dbhelp/userhelp.js中
'use strict'; let mongoose = require('mongoose'); let user = mongoose.model('user'); /* 查找用户 */ exports.findallusers = async () => { let query = user.find(); let res = []; await query.exec(function (err, users) { if (err) { res = []; } else { res = users; } }); return res }; /* 查找特定用户 */ exports.findfilterusers = async (params) => { let namereg = new regexp(params.name, 'i'); let query = user.find({ name: { $regex: namereg } }); let res = []; await query.exec(function (err, users) { if (err) { res = [] } else { res = users; } }); return res }; /* 查找单个用户 */ exports.finduser = async (params) => { let query = user.find({ id: params.id }); let res = {}; await query.exec(function (err, tuser) { if (err) { res = '没有该用户'; } else { res = tuser[0]; } }); return res }; /* 新增用户 */ exports.adduser = async (user) => { user = await user.save(); return user }; /* 编辑用户 */ exports.updateuser = async (user) => { user = await user.update({id: user.id}, { $set: { name: user.name, sex: user.sex, area: user.area, always: user.always, relationship: user.relationship, phone: user.phone, mobile: user.mobile, desc: user.desc } }); return user }; /* 删除用户 */ exports.deleteuser = async ({id}) => { let flag = false; console.log('flag==========>' + flag); await user.remove({id}, function (err) { if (err) { flag = false } else { flag = true } }); console.log('flag=====await=====>' + flag); return flag };
9. 路由配置中对应的方法
路由配置中对应的方法在app/controller/user.js中。
'use strict'; let xss = require('xss'); let mongoose = require('mongoose'); let user = mongoose.model('user'); let uuid = require('uuid'); import userhelper from '../dbhelper/userhelper.js' /* 多用户 */ exports.users = async (ctx, next) => { let data; if (ctx.request.body) { data = await userhelper.findfilterusers(ctx.request.body) } else { data = await userhelper.findallusers() } ctx.body = { success: true, data } }; /* 单用户 */ exports.user = async (ctx, next) => { let data = await userhelper.finduser(ctx.request.body) ctx.body = { success: true, data } }; /* 添加(更新)用户 */ exports.adduser = async (ctx, next) => { let newobj = ctx.request.body, user2; let id = newobj.id || uuid.v4(); let user = new user({ name: newobj.name, sex: newobj.sex, area: newobj.area, always: newobj.always, relationship: newobj.relationship, phone: newobj.phone, mobile: newobj.mobile, desc: newobj.desc, id: id }); if (newobj.id) { user2 = await userhelper.updateuser(user); } else { user2 = await userhelper.adduser(user); } if (user2) { ctx.body = { success: true, data: user2 } } }; /* 删除用户 */ exports.deleteuser = async (ctx, next) => { let id = xss(ctx.request.body.id); let data = await userhelper.deleteuser({id}); ctx.body = { success: true, data } };
总结:
其实没有什么花头,无非都是api的使用,这里比较多用async与await实现异步操作,阮老师的文章里有async的一切,。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。