Mongoose and Redis installation and use

I. Introduction to MongoDB

  • Install Mongoose

  1. brew tap mongodb/brew
  2. brew install mongodb-community
  3. brew services start mongodb-community
  4. Check whether the installation is successful: which mongod
  5. Launch project: mongod
  6. Here, the mac system may fail to create related folders due to system upgrade. Here you just need to turn off SIP protection and create it.
  7. It is recommended to cooperate with database tools to check our interaction with the database, Robo 3T
  8. Install npm i mongoose
  9. Create the dbs folder and create the file config.js to save our database address. And the models folder, which is the information we need to store
  10. In app.js, mongoose and database address are introduced for connection.
  11. Create instance in interface

    # npm in mongoose
    # mkdir dbs
    # mkdir dbs/models 
    # touch dbs/models/person.js
    # touch dbs/config.js
  • Use Mongoose to add, delete, modify and query

    config.js =) database address

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

    person.js =) first declare the Schema, declare a table in the database, create a model, and create an instance in the model

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

    App. JS = > introduce mongoose and database address to connect

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

    routes/users.js

    const router = require('koa-router')()
    // Introducing model
    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'
    })
    // Newly added
    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
      }
    })
    // delete
    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
      }
    })
    // Update
    router.post('/updatPerson', async function (ctx) {
      await Person.where({
        name: ctx.request.body.name
      }).update({
        age: ctx.request.body.age
      })
      ctx.body = {
        code: 0
      }
    })
    // query
    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

    Terminal start request interface

    # curl = > initiate request; - d = > post request
    # Newly added
    curl -d "name=youzi&age=18" http://localhost:3000/users/addPerson
    # delete
    curl -d "name=youzi" http://localhost:3000/users/removePerson
    # Update
    curl -d "name=youzi" http://localhost:3000/users/updatPerson
    # Novelty search
    curl -d "name=youzi" http://localhost:3000/users/findPerson

II. Basis of Redis

  • The relationship between session and cookie?

    Speaking of the login function that we often develop in our daily work, how does the server program identify the status of the client? HTTP is stateless. How can you guarantee that the next time a user visits our server's program, or this user? How does the session of the server stay on the client?

  • redis installation and use?

  1. brew install redis on Mac
  2. Use redis server to start
  3. Enter the project, install two middleware (KOA redis, KOA generic session) in the project
  • redis is used with session?

  1. app.js introduces two middleware for development

    const session = require('koa-generic-session')
    const Redis = require('koa-redis')
    app.keys = ['keys', 'keyskyes']; //Encrypt the session. Here is the value set by yourself
    app.use(session({
        store:new Redis()
       //Do not write configuration item content and save it in memory. Here we save it in redis
    }))
  2. koa-pv.js Middleware

    # Here is the pv number plus. Associate session with current user access
    # Store the session value in the cookie to distinguish different user identities
    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. Refresh the page to view. There is a value we just saved in the cookie. The key value at the beginning of koa is the content we store. Here, we can modify the key value at the beginning of koa. Just set the key and prefix prefix. The usage is as follows

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

  • What does session store? How to view and read the current stored value?

  1. A session object will be created under the CTX object. We can read and write ctx.session directly
  2. To view the values in the database, you can start the client program through redis cli. The keys * command can view all the current key values and get the values we want.
  • How to operate redis directly?

  1. Here is an example of creating an interface.
  2. Firstly, KOA redis is introduced;
  3. Create a redis client
  4. Write in interface

    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
      }
    })
    # Just ask directly. Because it's get, hahahaha
    # url http://localhost:3000/users/fix
    # Go to redis and you will see the value we just created

Tags: node.js Redis Session Mongoose Database

Posted on Fri, 06 Dec 2019 02:43:42 -0800 by tkm