您好,登錄后才能下訂單哦!
配合上一篇文章的聯系人應用(https://www.jb51.net/article/161160.htm),實現配套的基于nodejs的后臺增刪改查接口
1. 所需工具
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。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。