MongoDB使用云数据库

  1. 注册用户

  2. 创建数据库

    image-20201123111151143

  3. 添加用户

    image-20201123111210206

  4. 设置白名单地址

    image-20201123111417055

  5. 链接数据库

    image-20201123111552893

使用数据库

  1. 安装mongoose

    1
    yarn add mogoose
  2. 链接数据库

    • 复制上一步的字符串,并替换掉其中的数据。例如<password><dbname>

    • 在入口文件链接数据库

      1
      2
      3
      4
      5
      6
      7
      const mongoose = require('mongoose')
      // 通过配置文件导入链接字符串
      const { connectionStr } = require('./config')

      mongoose.connect(connectionStr, { useUnifiedTopology: true, useNewUrlParser: true }, () => {
      console.log('链接成功了');
      })
  3. 创建用户模型

    新建一个schema文件夹,在这个文件中写我们的数据库模型。例如user

    1
    2
    3
    4
    5
    6
    7
    8
    9
    const mongoose = require('mongoose')
    const { Schema, model } = mongoose

    const userSchema = new Schema({
    name: { type: String, required: true }
    })

    // 生成模型
    model.exports = model('User', userSchema)
  4. 实现增删改查

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    const User = require('../models/users')

    class UserCtl {
    async find (ctx) {
    ctx.body = await User.find()
    }

    async findById (ctx) {
    const user = await User.findById(ctx.params.id)
    if (!user) {
    ctx.throw(404, '用户不存在')
    }
    ctx.body = user
    }
    async create (ctx) {
    ctx.verifyParams({
    name: { type: 'string', required: true },
    })
    const user = await new User(ctx.request.body).save()
    ctx.body = user
    }
    async update (ctx) {
    ctx.verifyParams({
    name: { type: 'string', required: true },
    })
    const user = await User.findByIdAndUpdate(ctx.params.id, ctx.request.body)
    if (!user) ctx.throw(404, '修改的用户ID不存在')
    ctx.body = user
    }
    async delete (ctx) {
    const user = await User.findByIdAndRemove(ctx.params.id)
    if (!user) ctx.throw(404, '删除的用户ID不存在')
    ctx.status = 204
    }
    }
    module.exports = new UserCtl()