koa2入门(3)mongoose 增删改查
生活随笔
收集整理的這篇文章主要介紹了
koa2入门(3)mongoose 增删改查
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
項(xiàng)目地址:https://github.com/caochangkui/demo/tree/koa-mongoose
連接數(shù)據(jù)庫
數(shù)據(jù)庫名字為:koa-mongoose
const mongoose = require('mongoose')// 連接數(shù)據(jù)庫,URL以mongodb:// + [用戶名:密碼@] +數(shù)據(jù)庫地址[:端口] + 數(shù)據(jù)庫名。(默認(rèn)端口27017) // 連接mongodb數(shù)據(jù)庫的鏈接解析器會在未來移除,要使用新的解析器,通過配置{ 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.* 可以如下設(shè)置*/ mongoose.set('useNewUrlParser', true) mongoose.set('useFindAndModify', false) mongoose.set('useCreateIndex', true)let db = mongoose.connection mongoose.Promise = global.Promise // 防止Mongoose: mpromise 錯(cuò)誤db.on('error', function (err) {console.log('數(shù)據(jù)庫連接出錯(cuò)', err) })db.on('open', function () {console.log('數(shù)據(jù)庫連接成功') })db.on('disconnected', function () {console.log('數(shù)據(jù)庫連接斷開') })創(chuàng)建數(shù)據(jù)表
/* 聲明 Schema 創(chuàng)建數(shù)據(jù)表模型,即 User,就是數(shù)據(jù)表的名字 下面給 User 表聲明三個(gè)字段 username password age */ const userSchema = mongoose.Schema({username: {type: String,required: true},password: {type: String,require: true},age: {type: Number,require: true} })// 根據(jù) schema 生成 model const model = {User: mongoose.model('User', userSchema) }module.exports = model定義 mongoose 數(shù)據(jù)庫操作方法
const User = require('../dbs.js').User // 從dbs.js引入數(shù)據(jù)表/*** 數(shù)據(jù)庫操作*/// 增加用戶,方法一:save() const saveUser = async (ctx) => {// 通過實(shí)例化一個(gè) User 對象在添加用戶const newUser = new User({username: 'cedric',password: '123',age: 27})let code = 0 // 狀態(tài)碼let result = '' // 返回內(nèi)容try {let doc = await newUser.save()code = 0result = '保存成功, ' + doc} catch (err) {code = -1result = '保存失敗, ' + err}ctx.response.body = {code,result}return result }// 增加用戶,方法二:create(), 推薦此方法 // 使用save()方法,需要先實(shí)例化為文檔,再使用save()方法保存文檔。而create()方法,則直接在模型Model上操作,并且可以同時(shí)新增多個(gè)文檔 const createUser = async (ctx) => {let code = 0 // 狀態(tài)碼let result = '' // 返回內(nèi)容try {let doc = await User.create({username: 'cedric222',password: '123',age: 27}, {username: 'cedric333',password: '123',age: 27})code = 0result = '保存成功, ' + doc} catch (err) {code = -1result = '保存失敗, ' + errconsole.log(err)}ctx.response.body = {code,result}return result }// 根據(jù)用戶名查找用戶 const findUser = async (ctx) => {let code = 0 // 狀態(tài)碼let result = '' // 返回內(nèi)容try {let doc = await User.findOne({username: 'cedric222'})code = 0result = '查找結(jié)果: ' + doc} catch (err) {code = -1result = '查找失敗: ' + err}ctx.response.body = {code,result}return result }// 根據(jù)指定條件查找所有用戶 // find指的是查找指定表的所有數(shù)據(jù),返回的是數(shù)組 // findOne指的是查找指定表的單條數(shù)據(jù),返回一個(gè)對象 const findAllUser = async (ctx) => {let code = 0 // 狀態(tài)碼let result = '' // 返回內(nèi)容try {let doc = await User.find({})code = 0result = '查找結(jié)果: ' + doc} catch (err) {code = -1result = '查找失敗: ' + err}ctx.response.body = {code,result}return result }// 修改用戶數(shù)據(jù) // conditions: 查詢條件;updateDoc:需要修改的數(shù)據(jù), 都是一個(gè)對象 // multi (boolean): 默認(rèn)為false。是否更新多個(gè)查詢記錄。 // https://segmentfault.com/a/1190000012095054#articleHeader16 // https://mongoosejs.com/docs/api.html#model_Model.update const updateUser = async (ctx) => {let code = 0 // 狀態(tài)碼let result = '' // 返回內(nèi)容try {let doc = await User.update({age: 27}, {age: 28}, {multi: true})code = 0result = '修改結(jié)果: ' + docconsole.log(doc)} catch (err) {code = -1result = '修改失敗: ' + err}ctx.response.body = {code,result}return result }// 刪除用戶數(shù)據(jù) const removeUser = async (ctx) => {let code = 0 // 狀態(tài)碼let result = '' // 返回內(nèi)容try {let doc = await User.remove({username: 'cedric444'})code = 0result = '刪除成功: ' + docconsole.log(doc)} catch (err) {code = -1result = '刪除失敗: ' + err}ctx.response.body = {code,result}return result }module.exports = {saveUser,createUser,findUser,findAllUser,updateUser,removeUser }入口文件app.js
const Koa = require('koa') const app = new Koa();const Router = require('koa-router') // koa路由中間件const router = new Router({prefix: '/api' }) // 父路由, 給路由統(tǒng)一加個(gè)前綴 /apiconst bodyParser = require('koa-bodyparser') // 處理post請求,把 koa2 上下文的表單數(shù)據(jù)解析到 ctx.request.body 中 app.use(bodyParser())// 引入數(shù)據(jù)庫操作方法 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 處理的業(yè)務(wù)是當(dāng)所有路由中間件執(zhí)行完成之后,若ctx.status為空或者404的時(shí)候,豐富response對象的header頭 app.use(router.allowedMethods())app.listen(3333, () => {console.log('This server is running at http://localhost:' + 3333) })轉(zhuǎn)載于:https://www.cnblogs.com/cckui/p/10429064.html
總結(jié)
以上是生活随笔為你收集整理的koa2入门(3)mongoose 增删改查的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 京东强势开启百亿补贴 刘强东怎么就盯上了
- 下一篇: 使用Tomcat-redis-sessi