• 【Koa】【MongoDB】koa框架连接MongoDB


    Koa框架安装及配置

    cnpm install koa -g
    
    • 1
    koa my-app
    
    • 1
    cd my-app
    npm install
    
    • 1
    • 2

    虽然使用npm start启动项目有效,但官方推荐使用npm run dev启动项目,因为dev的命令用到了nodemon,可以实时进行热更新。

    在这里插入图片描述

    不过,未修改任何配置下运行npm run dev命令会报错,这个时候,我们只需要对dev做如下修改即可。修改后,再次敲入命令,就可以运行起来了。

    在这里插入图片描述


    运行后,在浏览器敲入:http://localhost:3000,将看到如下界面,说明服务启动成功。

    在这里插入图片描述

    打开/bin/www,找到如图所示的地方,3000是koa的默认端口,当有其他服务占用该端口时,可以考虑修改这个端口号。

    在这里插入图片描述

    入门Koa的用法

    在routes的文件夹下新建一个路由文件,并初始化路由

    ./routes/index.js

    var router = require('koa-router')()
    
    //...接口编写处
    
    module.exports = router;
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在app.js文件中注册路由文件

    var index = require('./routes/index')
    
    app.use(index.routes(),index.allowedMethods())
    
    • 1
    • 2
    • 3

    获取http请求参数

    参数形式:(用url传递参数有长度限制和敏感信息不安全等缺点)

    1.查询字符串:?q=keyword

    获取:ctx.request.query

    2.路由参数:/users/:id (一般是必选的)

    获取:ctx.request.params

    3.请求体:{name: …} (两种形式:json和form,json:application/json, form:application/x-www-form-urlencoded)

    获取:ctx.request.body(需安装中间件koa-bodyparser,但koa框架已经为我们安装了)


    连接MongoDB数据库

    安装mongoose模块

    cnpm install mongoose --save-dev
    
    • 1

    新建一个文件夹db,文件目录:./db/models/user.js、./db/index.js

    在这里插入图片描述

    在Koa中创建模式(表),无需在MongoDB Compass中手动添加表

    ./db/models/user.js

    const mongoose = require('mongoose')
    
    const userSchema = new mongoose.Schema({
    	//创建模式,下面是表的字段名,并定义字段类型
        username:String,
        pwd:String,
        phone:Number,
    })
    const User = mongoose.model('user',userSchema)
    
    module.exports = {
        User
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    值得注意的是,mongoose.model(‘user’,userSchema)会让MongoDB自动添加一个数据库名为users,不要看错了,是usersusersusers重要的事情说三遍,无论写什么,MongoDB新增表名就是会多加一个s

    ./db/index.js

    const mongoose = require('mongoose')
    
    module.exports = () => {
        mongoose.connect('mongodb://localhost:27017/表名', 
        				{ useNewUrlParser: true })
        //举个栗子
        //mongoose.connect('mongodb://localhost:27017/users', 
        //					{ useNewUrlParser: true })
            .then(() => {
                console.log('数据库连接成功')
            }).catch(err => {
                console.log('连接出错了', err)
            })
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    重新启动服务,若数据库连接错误,则需要手动启动mongoDB服务

    在这里插入图片描述


    入门Koa对MongoDB的操作(增删改查)

    ./routes/index.js

    const {User} = require('../db/models/user')
    
    • 1

    增 - create()

    router.post('/add',async(ctx)=>{
    	//字段名需要和在模式中定义的保持一致
    	await User.create({字段名1:...,字段名2:...}).then(res=>{
    		ctx.body = {
    			...res
    		}
    	})
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    删 - where().remove() / findByIdAndRemove({id}) / findOne().remove() / find().remove()

    router.post('/delete',async(ctx)=>{
    	//先查询,再删除
    	await User.where({字段名1:...,字段名2:...}).remove()
    		.then(res=>{
    			ctx.body = {
    				...res
    			}
    		})
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    改 - where().update() / updateOne({},{}) / findByIdAndUpdate({id},{})

    router.post('/update',async(ctx)=>{
    	//先查询,再修改
    	await User.where({字段名1:...,字段名2:...})
    		.update({字段名1:...,字段名2:...})
    		.then(res=>{
    			ctx.body = {
    				...res
    			}
    		})
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    查 - find() / findOne({}) / findById({id})

    find():查找全部

    findOne():根据条件查找

    router.post('/findOne',async(ctx)=>{
    	//先查询,再修改
    	await User.findOne({字段名1:...,字段名2:...},{字段名3:...,字段名4:...})
    		.then(res=>{
    			ctx.body = {
    				...res
    			}
    		})
    })
    
    router.get('/find',async(ctx)=>{
    	//先查询,再修改
    	await User.find().then(res=>{
    			ctx.body = {
    			...res
    		}
    	})
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    需要注意的是,操作数据库是异步操作,需要使用await,否则会报Not Found错误


    请求参数类型控制

    我们已经在./db/models/user.js文件中对表的字段定义好了数据类型,对表进行增改操作时,Mongoose会帮我们将数据对应的进行类型转换。

    所有类型的字段均可传null,不可传undefined / NaN

    可行操作:均可传null
    接收方(String)- 发送方(任意类型)
    接收方(Number)- 发送方(为数字的String或者为""
    接收方(Boolean)- 发送方(为true/false的String)

    不可行操作:均不可传undefined以及NaN
    接收方(Number)- 发送方(不为数字的String)
    接收方(Boolean)- 发送方(不为true/false的String或者为""

    在这里插入图片描述

  • 相关阅读:
    SSL证书品牌参差不齐?品牌太多不知道怎么选择?
    排序——直接插入、折半插入、希尔排序
    pycharm报错提示:无法加载文件\venv\Scripts\activate.ps1,因为在此系统上禁止运行脚本
    数据库SQL优化总结
    <七>理解多态
    opencv的色彩空间
    PTA古风排版
    java毕业设计校园实习管理系统mybatis+源码+调试部署+系统+数据库+lw
    apache jmeter怎么用
    Linux 部署Vue项目
  • 原文地址:https://blog.csdn.net/qq_45870740/article/details/126875277