koa+mongoose实现简单增删改查接口的示例代码
配合上一篇文章的联系人应用(https://www.jb51.net/article/161160.htm),实现配套的基于nodejs的后台增删改查接口
1. 所需工具
- node.js
- mongoDB
2. 主要node模块
koa(https://koa.bootcss.com,一个nodejs的开发框架),mongoose(https://mongoosejs.com,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的一切,http://es6.ruanyifeng.com/#docs/async。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)