• Node.js学习笔记【六】


    NoSQL简介

    NoSQL是对不同于传统的关系型数据库的数据库管理系统的统称。

    NoSQL数据库的分类

    • 列存储(HBase):按列进行存储,属于比较高级的数据库
    • 文档存储(MongoDB):按JSON来存储
    • Key-value存储(Redis):通常用于缓存也可以实现消息通信
    • 图存储(FlockDB)
    • 对象存储(db4o)
    • XML存储(BaseX)

    使用NoSQL的好处

    • 简单(没有原子性、一致性、隔离性等复杂规范)
    • 便于横向拓展(横向拓展:横向增加服务器数量来增加计算能力以及存储容量)
    • 适合超大规模数据的存储
    • 很灵活地存储复杂结构的数据(Schema Free)

    MongoDB简介

    MongoDB一词来自于英文单词“Humongous”,中文含义为“庞大”,MongoDB是面向文档存储的开源数据库,MongoDB由C++编写而成,但是支持各种编程语言。

    MongoDB好处

    • 性能好(利用内存计算的优势)
    • 支持大规模数据存储(它的可拓展性好)
    • 可靠安全(MongoDB有本地复制、自动故障转移等自带的功能)
    • 方便存储复杂数据结构(Schema Free)

    MongoDB下载

    可以在MongoDB官网下载,支持常见平台(Windows、Linux、OSX)

    云MongoDB

    把MongoDB安装在服务器(服务商提供的服务器)上,可以支持更大规模数据存储,也比较安全。

    • 阿里云、腾讯云(收费):比较适合在生产环境使用
    • MongoDB官方的MongoDB Atlas(收费+免费)

    云数据库——MongoDB Atlas

    MongoDB官网注册用户

    然后在Atlas创建集群

    image-20210806225343766

    添加数据库用户

    image-20210806225736766

    image-20210806225957147

    设置IP地址白名单

    image-20210806230108431

    image-20210806230843334

    获取连接地址

    image-20210806230555971

    image-20210806230819989

    image-20210806231132074

    用Mongoose连接MongoDB

    • 安装Mongoose

    npm i mongoose --save

    • 用Mongoose连接MongoDB

    创建config.js配置连接字符串

    module.exports = {
    connectionStr:'mongodb://root:<password>@zhihu-shard-00-00.htx1s.mongodb.net:27017,zhihu-shard-00-01.htx1s.mongodb.net:27017,zhihu-shard-00-02.htx1s.mongodb.net:27017/myFirstDatabase?ssl=true&replicaSet=atlas-t4dg3c-shard-0&authSource=admin&retryWrites=true&w=majority'
    }
    

    在index.js中引用使用

    const mongoose = require('mongoose')
    const {connectionStr} = require('./config');
    //接收的第一个参数就是之前在网站生成好的连接字符串
    mongoose.connect(connectionStr,{useUnifiedTopology: true,useNewUrlParser: true},()=>{
      console.log('MongoDB 连接成功了!');
    })
    //监听错误方法,打印错误信息
    mongoose.connection.on('error',console.error);
    

    运行成功~

    image-20210807074815887

    设计用户模块的Schema

    操作步骤:

    • 分析用户模块的属性
    • 编写用户模块的Schema
    • 使用Schema生成用户Model

    新建models->users.js编写用户模块的Schema:

    const mongoose = require('mongoose');
    //mongoose提供的Schema类生成文档Schema
    const { Schema,model } = mongoose
    

    const userSchema = new Schema({
    //required表示这个属性是必选的
    //default可以设置默认值
    name:{type:String,required:true},

    });
    //建立模型
    //User:为文档集合名称
    module.exports = model('User',userSchema);

    用MongoDB实现用户的增删改查

    操作步骤

    • 用Mongoose实现增删改查接口
    • 用Postman测试增删改查接口

    来到controllers->users.js将之前写的内存数据库改为真实的模型

    const User = require('../models/users');
    

    引入模型后就可以使用它的方法实现增删改查啦

    const User = require('../models/users');
    

    创建用户:

    //创建用户
      async create(ctx){
        //校验请求体的name位字符串类型并且是必选的
        ctx.verifyParams({
          //必选:required 删掉也是默认为true
          name:{ type:'string',required:true },
        });
        const user = await new User(ctx.request.body).save();
        ctx.body = user;
      }
    

    image

    查看用户:

      //获取用户列表
     async find(ctx){
        ctx.body = await User.find();
      }
    

    image

    查看特定用户:

    //获取特定用户
      async findById(ctx){
        const user = await User.findById(ctx.params.id);
        //用户不存在
        if(!user){ ctx.throw(404,'用户不存在');}
        ctx.body = user;
      }
    

    image

    修改用户:

    //更新用户
      async update(ctx){
    
    ctx.verifyParams({
      //必选:required 删掉也是默认为true
      name:{ type:&#39;string&#39;,required:true },
    
    });
    const user = await User.findByIdAndUpdate(ctx.params.id,ctx.request.body);
    if(!user){ctx.throw(404,&#39;用户不存在&#39;);}
    ctx.body = user;
    

    }

    image

    删除用户:

      //删除用户
      async delete(ctx){
    
    const user = await User.findByIdAndRemove(ctx.params.id);
    if(!user){ctx.throw(404,&#39;用户不存在&#39;);}
    ctx.status = 204
    

    }

    image

  • 相关阅读:
    H5图片上传、压缩
    数据库基本操作
    数组遍历
    CURL
    获取IP
    Memcached的实战笔记
    修bug总结 (基于java语言)
    java开发工作的总结
    多线程测试类
    可清除的单例对象获取类
  • 原文地址:https://www.cnblogs.com/Small-Windmill/p/15112702.html
Copyright © 2020-2023  润新知