Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”. This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

preface

Before we have introduced the installation of MongoDB, this article will talk about how MongoDB combined with Koa to achieve login authentication function in the actual project, we will realize the storage of userName and userPwd in MongoDB database, and then the user login input account and password, It will look up in the database whether to use the account and password, so as to achieve the login authentication function.

Insert documents into MongoDB

Open the Robo 3T client, create a new database awu-Manager, create the set Users and insert the document:

{
    userName: "admin",
    userPwd: "admin"
}
Copy the code

2. Start a KOA2 service

If you are using KOA for the first time, you need to install koA-Generator

yarn global add koa-generator

koa2 manager-server

yarn install

yarn dev
Copy the code

Here you have successfully launched a KOA2 project, enter http://localhost:3000/ in the address bar, you can access it

How to connect to MongoDB?

We need to create the config folder in the root directory to create the configuration file and database connection file respectively.

/config/index.js
/** * Config file */
module.exports = {
  URL: 'mongo: / / 127.0.0.1:27017 / Awu - manager'
}
Copy the code
/config/db.js
/** * Database connection */
const mongoose = require('mongoose')
const config = require('./index')
const log4js = require('. /.. /utils/log4j')

// Connect to the database through mongooose
mongoose.connect(config.URL,{
  useNewUrlParser: true.useUnifiedTopology: true
  })
  
// Check whether the database is connected successfully
const db = mongoose.connection
db.on('error'.() = > {
  log4js.error('**** database connection failure ****')
})
db.on('open'.() = > {
  log4js.info('**** database connection successful ****')})Copy the code

At this point we have successfully connected to the database, I here log monitoring utilizationlog4jsIf you are interested in log4js, you can check it out for yourself. I will also update the usage of log4js in my blog

Mongoose is not installed in KOA2 by default, we need to install it manually.

yarn global mongoose -S
Copy the code

For the basic use of Mongoose, please refer to the official monGOOSE documentation

How to check data in MongoDB?

Define the model

We need to define a model layer for the database, create a new models folder under the root directory, and create the userSchema.js file, which needs to correspond to the database data

const mongoose = require('mongoose')
const userSchema = mongoose.Schema({
  "userId": Number.// User ID, self-growth
  "userName": String.// User name
  "userPwd": String.// User password
  "userEmail": String.// The user's mailbox
  "mobile": String./ / cell phone number
  "sex": Number.// Gender 0: male 1: female
  "deptId": []./ / department
  "jobs": String./ / position
  "state": {
    type: Number.default: 1
  }, // 1: in-service 2: resignation 3: probation
  "role": {
    type: Number.default: 1
  }, // Role 0: system administrator 1: common user
  "roleList": [].// System role
  "createTime": {
    type: Date.default: Date.now()
  }, // Create time
  "lastLoginTime": {
    type: Date.default: Date.now()
  }, // Update time
   remark: String // use the remark field to facilitate expansion
})
// Export the definition model. Note that the third parameter corresponds to the collection in the database.
module.exports = mongoose.model("users",userSchema,"users")
Copy the code

Query part of the core code


const router = require('koa-router') ()const User = require('. /.. /models/userSchema')

Util is the encapsulated utility function
const util = require('. /.. /utils/util')

// Add the request prefix
router.prefix('/users')

router.post('/login'.async (ctx) => {
  try {
    const { userName, userPwd } = ctx.request.body
    // Query in the model
    const res = await User.findOne({
      userName,
      userPwd
    })
    if (res) {
      ctx.body = util.success(res)
    } else {
      ctx.body = util.fail("Incorrect account number or password")}}catch (error) {
    ctx.body = util.fail(error.msg)
  }
})

module.exports = router
Copy the code

So let’s test that out

Test data 1: Account: admin Password: aaAAA

Test data 2: Account: admin Password: adminThrough log printing, we can see that the function of user login verification has been successfully realized. In the front end, we intercept the response and complete the function of page jump by judging the status code.

The last

⚽ this article mainly introduces Koa2 combined with MongoDB to do login verification function ~ ⚾ if you are interested in this article welcome to like attention + collect, more wonderful knowledge is waiting for you! 😘 🏀GitHub blogs at github.com/Awu1227. 🏉 I have other columns, please read ~ 🏐 play the beauty of CSS 🎱Vue from giving up to getting started 🎳 simple JavaScript