項目地址:https://github.com/caochangkui/demo/tree/koa-mongoosehtml
數據庫名字爲:koa-mongoosenode
const mongoose = require('mongoose') // 鏈接數據庫,URL以mongodb:// + [用戶名:密碼@] +數據庫地址[:端口] + 數據庫名。(默認端口27017) // 鏈接mongodb數據庫的連接解析器會在將來移除,要使用新的解析器,經過配置{ useNewUrlParser:true }來鏈接 ;其餘警告參考:https://mongoosejs.com/docs/deprecations.html mongoose.connect('mongodb://127.0.0.1:27017/koa-mongoose', {useNewUrlParser:true,useCreateIndex: true}) /** * 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 db = mongoose.connection mongoose.Promise = global.Promise // 防止Mongoose: mpromise 錯誤 db.on('error', function (err) { console.log('數據庫鏈接出錯', err) }) db.on('open', function () { console.log('數據庫鏈接成功') }) db.on('disconnected', function () { console.log('數據庫鏈接斷開') })
/* 聲明 Schema 建立數據表模型,即 User,就是數據表的名字 下面給 User 表聲明三個字段 username password age */ const userSchema = mongoose.Schema({ username: { type: String, required: true }, password: { type: String, require: true }, age: { type: Number, require: true } }) // 根據 schema 生成 model const model = { User: mongoose.model('User', userSchema) } module.exports = model
const User = require('../dbs.js').User // 從dbs.js引入數據表 /** * 數據庫操做 */ // 增長用戶,方法一:save() const saveUser = async (ctx) => { // 經過實例化一個 User 對象在添加用戶 const newUser = new User({ username: 'cedric', password: '123', age: 27 }) let code = 0 // 狀態碼 let result = '' // 返回內容 try { let doc = await newUser.save() code = 0 result = '保存成功, ' + doc } catch (err) { code = -1 result = '保存失敗, ' + err } ctx.response.body = { code, result } return result } // 增長用戶,方法二:create(), 推薦此方法 // 使用save()方法,須要先實例化爲文檔,再使用save()方法保存文檔。而create()方法,則直接在模型Model上操做,而且能夠同時新增多個文檔 const createUser = async (ctx) => { let code = 0 // 狀態碼 let result = '' // 返回內容 try { let doc = await User.create({ username: 'cedric222', password: '123', age: 27 }, { username: 'cedric333', password: '123', age: 27 }) code = 0 result = '保存成功, ' + doc } catch (err) { code = -1 result = '保存失敗, ' + err console.log(err) } ctx.response.body = { code, result } return result } // 根據用戶名查找用戶 const findUser = async (ctx) => { let code = 0 // 狀態碼 let result = '' // 返回內容 try { let doc = await User.findOne({ username: 'cedric222' }) code = 0 result = '查找結果: ' + doc } catch (err) { code = -1 result = '查找失敗: ' + err } ctx.response.body = { code, result } return result } // 根據指定條件查找全部用戶 // find指的是查找指定表的全部數據,返回的是數組 // findOne指的是查找指定表的單條數據,返回一個對象 const findAllUser = async (ctx) => { let code = 0 // 狀態碼 let result = '' // 返回內容 try { let doc = await User.find({}) code = 0 result = '查找結果: ' + doc } catch (err) { code = -1 result = '查找失敗: ' + err } ctx.response.body = { code, result } return result } // 修改用戶數據 // conditions: 查詢條件;updateDoc:須要修改的數據, 都是一個對象 // multi (boolean): 默認爲false。是否更新多個查詢記錄。 // https://segmentfault.com/a/1190000012095054#articleHeader16 // https://mongoosejs.com/docs/api.html#model_Model.update const updateUser = async (ctx) => { let code = 0 // 狀態碼 let result = '' // 返回內容 try { let doc = await User.update({age: 27}, {age: 28}, {multi: true}) code = 0 result = '修改結果: ' + doc console.log(doc) } catch (err) { code = -1 result = '修改失敗: ' + err } ctx.response.body = { code, result } return result } // 刪除用戶數據 const removeUser = async (ctx) => { let code = 0 // 狀態碼 let result = '' // 返回內容 try { let doc = await User.remove({username: 'cedric444'}) code = 0 result = '刪除成功: ' + doc console.log(doc) } catch (err) { code = -1 result = '刪除失敗: ' + err } ctx.response.body = { code, result } return result } module.exports = { saveUser, createUser, findUser, findAllUser, updateUser, removeUser }
const Koa = require('koa') const app = new Koa(); const Router = require('koa-router') // koa路由中間件 const router = new Router({ prefix: '/api' }) // 父路由, 給路由統一加個前綴 /api const bodyParser = require('koa-bodyparser') // 處理post請求,把 koa2 上下文的表單數據解析到 ctx.request.body 中 app.use(bodyParser()) // 引入數據庫操做方法 const UserController = require('./server/controller/users.js') // 路由,訪問:http://localhost:3333/api/save router.get('/save', UserController.saveUser) router.get('/create', UserController.createUser) router.get('/find', UserController.findUser) router.get('/findall', UserController.findAllUser) router.get('/update', UserController.updateUser) router.get('/remove', UserController.removeUser) // 加載路由中間件 app.use(router.routes()) // allowedMethods 處理的業務是當全部路由中間件執行完成以後,若ctx.status爲空或者404的時候,豐富response對象的header頭 app.use(router.allowedMethods()) app.listen(3333, () => { console.log('This server is running at http://localhost:' + 3333) })