This is my third article about getting started

  • Koa2 Write basic Back-end interface (1)

MongoDB

Those who have been exposed to Node.js have also been exposed to this database, which is relatively easy to use for the front-end, and the cost is very low with the Mongoose plug-in.

The installation

yarn add mongoose
Copy the code

Basic use:

// Import and connect to the database
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

// Define a Schema
const kittySchema = mongoose.Schema({
  name: String
})

// Schema compiles to a Model
const Kitten = mongoose.model('Kitten', kittySchema);

// Instantiate with new
const felyne = new Kitten({ name: 'Felyne' });
// Add, delete, change, and query the database through the model instance
// felyne.find()...
Copy the code

As can be seen from the above, mongoose’s configuration includes three parts: CONNECT, Models and Schema

Connect: Used to create a database connection

Schema: Schema is mainly used to define the structure of data in the MongoDB collection and the definition of fields in the database.

Models: Models is a constructor compiled from the Schema. Their instances represent documents that can be saved and read from the database. All of the creation and reading of documents from the database is done through the Model. A model is a model generated by a schema that performs operations on a database.

controllers

Because the code would be messy with multiple interfaces, we follow the modularity principle here. The business logic is not handled in the Router, and the route callback function is separated from the controllers file.

// controllers
const services = require('.. /services')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt')

function register(ctx, next) {
  const { username, password } = ctx.request.body
  const user = await services.getUserByName(username)
  if (user) {
    ctx.body = {
      code: 200.message: 'Username already exists',}}else {
    const pwdHash = bcrypt.hashSync(password, 10)
    const result = await services.addUser({ username, password: pwdHash })
    if (result) {
      ctx.body = {
        code: 200.message: 'Registration successful',
      }
    }
  }
  next()
}

module.exports = {
  register
}
Copy the code

services

Controllers only do business, and database operations are placed in the Services file.

//services
const Users = require('.. /models/user')

async function getUserByName(username) {
  return await Users.findOne({ username })
}

async function addUser(user) {
  return await Users.create(user)
}

module.exports = {
  getUserByName,
  addUser
}
Copy the code