Mongoose和Redis安装以及使用

1、MongoDB入门

  • 安装Mongoose

  1. brew tap mongodb/brew
  2. brew install mongodb-community
  3. brew services start mongodb-community
  4. 检查是否安装成功:which mongod
  5. 启动项目:mongod
  6. 这里mac系统可能会由于系统升级存在建立相关文件夹失败的错误的问题。这里只需先关闭SIP保护,在进行建立便可。
  7. 这里建议配合数据库工具去查看咱们与数据库交互状况,Robo 3T
  8. 安装npm i mongoose
  9. 建立dbs文件夹,在内创件config.js来保存咱们数据库地址。以及models文件夹,里面就是咱们须要存储的信息
  10. 在app.js引入mongoose和数据库地址,进行链接。
  11. 接口中作建立实例redis

    # npm in mongoose
    # mkdir dbs
    # mkdir dbs/models 
    # touch dbs/models/person.js
    # touch dbs/config.js
  • 使用Mongoose增删改查

    config.js=》数据库地址mongodb

    module.exports = {
        dbs: 'mongodb://127.0.0.1:27017/dbs'
    }

    person.js=》先声明Schema,在数据库中声明一个表,建立模型,在模型中建实例数据库

    const mongoose = require('mongoose')
    const personSchema =new mongoose.Schema({
        name:String,
        age:Number
    })
    module.exports=mongoose.model('Perosn',personSchema)

    app.js=>引入mongoose和数据库地址,进行链接npm

    const mongoose = require('mongoose')
    const dbConfig = require('./dbs/config')
    mongoose.connect(dbConfig.dbs, {
      useNewUrlParser: true
    })

    routes/users.jscookie

    const router = require('koa-router')()
    // 引入模型
    const Person = require('../dbs/models/person')
    router.prefix('/users')
    
    router.get('/', function (ctx, next) {
      ctx.body = 'this is a users response!'
    })
    
    router.get('/bar', function (ctx, next) {
      ctx.body = 'this is a users/bar response'
    })
    // 新增
    router.post('/addPerson', async function (ctx) {
      const person = new Person({
        name: ctx.request.body.name,
        age: ctx.request.body.age
      })
    
      let code;
      try {
        await person.save()
        code = 0;
      } catch {
        code = -1;
      }
      ctx.body = {
        code: code
      }
    })
    // 删除
    router.post('/removePerson', async function (ctx) {
      let resa = await Person.where({
        name: ctx.request.body.name
      }).remove()
      let code;
      try {
        code = 0;
      } catch (error) {
        code = -1;
      }
      ctx.body = {
        code: code
      }
    })
    // 修改更新
    router.post('/updatPerson', async function (ctx) {
      await Person.where({
        name: ctx.request.body.name
      }).update({
        age: ctx.request.body.age
      })
      ctx.body = {
        code: 0
      }
    })
    // 查询
    router.post('/findPerson', async function (ctx) {
      let resonlv1 = await Person.findOne({
        name: ctx.request.body.name
      })
      let resonlv2 = await Person.find({
        name: ctx.request.body.name
      })
      ctx.body = {
        code: 0,
        resonlv1,
        resonlv2
      }
    })
    
    module.exports = router

    终端启动请求接口session

    # curl=》发起请求;-d =》post请求
    # 新增
    curl -d "name=youzi&age=18" http://localhost:3000/users/addPerson
    # 删除
    curl -d "name=youzi" http://localhost:3000/users/removePerson
    # 更新修改
    curl -d "name=youzi" http://localhost:3000/users/updatPerson
    # 查新
    curl -d "name=youzi" http://localhost:3000/users/findPerson

2、Redis基础

  • session和cookie的关系?

    提及咱们平时工做中常开发的登录功能,服务端的程序是如何识别客户端的状态呢?HTTP是无状态的,用户访问了咱们服务端的程序,怎么保证下次访问的时候仍是这个用户呢?服务端的session又是如何保持在客户端呢?app

  • redis安装和使用?

  1. Mac下使用brew install redis
  2. 使用redis-server启动便可
  3. 进入项目,在项目内安装2个中间件(koa-redis、koa-generic-session)
  • redis配合session使用?

  1. app.js引入2个中间件,进行开发dom

    const session = require('koa-generic-session')
    const Redis = require('koa-redis')
    app.keys = ['keys', 'keyskyes']; //对session进行加密,这里是值本身定哦
    app.use(session({
        store:new Redis()
       //不写配置项内容存进内存,这里咱们存到redis中
    }))
  2. koa-pv.js中间件koa

    # 这里记录pv数加加。将session和当前用户访问进行关联
    # 将session的值存在cookie中,区分不一样的用户身份
    function pv(ctx) {
        ctx.session.count++
        global.console.log('pv' + ctx.path)
    }
    module.exports = function () {
        return async function (ctx, next) {
            pv(ctx)
            await next()
        }
    }
  3. 此时刷新页面查看。cookie中已经有咱们刚存进去的值了koa开头的就是咱们储存进去的内容,这里koa开头的key值咱们是能够去修改的。经过key和前缀prefix设置便可,用法以下curl

    app.use(session({
    
      key: 'mt',
    
      prefix: 'mtpr',
    
      store: new Redis()
    
    }))

    截屏2019-12-05下午4.08.36.png

  • session存储的是什么?如何查看和读取当前储存值的是什么?

  1. ctx对象下会建立一个session对象,咱们直接读写ctx.session便可
  2. 查看数据库中的值可经过redis-cli启动客户端程序,keys * 命令可查看当前全部key值,get获取咱们想要的值。
    截屏2019-12-05下午4.42.51.png
  • 若是直接操做操做redis,怎么操做?

  1. 这里举例是建立一个接口。
  2. 首先引入koa-redis;
  3. 建立一个redis客户端
  4. 接口中写入

    const Redis = require('koa-redis')
    const Store = new Redis().client;
    router.get('/fix', async function (ctx) {
      const st = await Store.hset('fix', 'nanme', Math.random())
      ctx.body = {
        code: 0
      }
    })
    # 直接请求便可。由于是get,哈哈哈哈
    # url http://localhost:3000/users/fix
    # 去redis中查询就能看到咱们刚才建立的值啦

相关文章
相关标签/搜索