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, 'https://www.jb51.net/' + 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中。