zoukankan      html  css  js  c++  java
  • express中操作数据库--Mongoose

    基本操作

    1.安装

    npm i mongoose --save
    
    // 1.引入
    let mongoose = require("mongoose");
    
    //2.链接数据库
    //mongoose.connect("mongodb://username:123456@localhost/m_data");
    mongoose.connect("mongodb://localhost/eggcms", { useNewUrlParser: true }).then(
      (val) => {
        console.log("连接成功");
      },
      (err) => {
        console.log("连接失败");
      }
    );
    
    // 3操作users表(集合) 定义一个schema(模型对象)
    /**
     * Schema里面传入一个对象,Schema中的对象和表里的字段一一对应
     */
    let userSchema = mongoose.Schema({
      name: String,
      age: Number,
    });
    /**
     * 4.定义数据库模型 操作数据库 第三个数据是集合的名称
     */
    //创建Model对象
    let userModel = mongoose.model("users", userSchema, "users");
    
    /**
     * 5 查询数据
     */
    userModel.find({}, (err, docs) => {
      if (!err) {
        console.log(docs);
      } else {
        console.log(err);
      }
    });
    
    /**6 增加数据--分两步 */
    //6.1 实例化 model 通过实例化users model增加数据
    let u = new userModel({
      name: "李四",
      age: 35,
    });
    
    //6.2执行增加操作
    u.save((err) => {
      if (err) {
        console.log("增加失败", err);
      } else {
        console.log("增加成功");
      }
    });
    
    /**
     *7 修改数据
     */
    userModel.updateOne(
      { _id: "60361defe13e534ff8ed7e82" },
      { name: "王五" },
      function (err, doc) {
        if (err) {
          console.log("修改失败", err);
        } else {
          console.log("修改成功", doc);
        }
      }
    );
    
    /**
     * 8 删除数据
     */
    userModel.deleteOne({ _id: "60361bbf2e344f0f5b265d06" }, function (err, doc) {
      if (err) {
        console.log("删除失败", err);
      } else {
        console.log("删除成功", doc);
      }
    });
    
    

    统计

    //4.5统计文档的个数
    /* 
        Model.count()
    */
    personModel.count({}, (err) => {
        if (!err) {
            console.log(count)
        } else {
            throw err
        }
    })
    

    预定义修饰符和自定义修饰符

    /**
    *//mongoose中的预定义模式修饰符
    **/
    let newSchema = mongoose.Schema({
      title: {
        type: String,
        trim: true,//去掉两端空格
      },
      author: String,
      pic: String,
      content: String,
    });
    
    /**
    *mongoose   getter与setters自定义修饰符
    *//可以通过set在增加数据是进行格式化,get(不建议使用)在获取model的时候进行格式化
    **/
    //例子:
    let focusSchema = mongoose.Schema({
      title: String,
      pic: String,
      redirect: {
        type: String,
        set(parmas) {
          if (!parmas) {
            return "";
          }
          if (parmas.indexOf("http://") != 0 && parmas.indexOf("https://") != 0) {
            return `http://${parmas}`;
          } else {
            return parmas;
          }
        },
      },
    });
    
    
    
    

    设置索引

    (这只索引后查询的速度变快,增加的速度会变慢)

    //可以在定义schema的时候指定创建索引
    
    sn:{
     type:Number,
     //唯一索引
     unique:true
       },
    
    name:{
     type:Number,
     //唯一索引
     index:true
       },
    
    

    Mongoose 内置 CURD

    Model.deleteMany() 
    Model.deleteOne()
    Model.find()
    Model.findById()
    Model.findByIdAndDelete()
    Model.findByIdAndRemove() 
    Model.findByIdAndUpdate() 
    Model.findOne()
    Model.findOneAndDelete()
    Model.findOneAndRemove() 
    Model.findOneAndUpdate() 
    Model.replaceOne()
    Model.updateMany()
    Model.updateOne()
    
    

    扩展 Mongoose CURD 方法

    var mongoose = require('./db.js');
    var UserSchema = mongoose.Schema({
        name: {
            type: String
        }, 
       age: Number,
       status: {
            type: Number,
            default: 1
        }
    })
    // 静态方法 
    UserSchema.statics.findByUid=function(uid,cb){
    //this相当于获取当前的model
    this.find({"_id": uid}, function (err, docs) {
        cb(err, docs)
    })
    }
    // 实例方法(基本不用) 
    UserSchema.methods.print = function () {
        console.log('这是一个实例方法');
        console.log(this);
    }
    ;
    module.exports = mongoose.model('User', UserSchema, 'user');
    
    

    数据校验

    required : 表示这个数据必须传入
    max: 用于 Number 类型数据,最大值
    min: 用于 Number 类型数据,最小值
    
    enum:枚举类型,要求数据必须满足枚举值 enum: ['0', '1', '2']
    
    match:增加的数据必须符合 match(正则)的规则
    
    maxlength:最大值
    minlength:最小值
    
    //例:
    var UserSchema = new mongoose.Schema({
        name: {
            type: String, required: true,
        },
     age: {
            type: Number,
    // 是否必须的校验器
            required: true,
    // 数字类型的最大值校验器 
            max: 120,
    // 数字类型的最小值校验器
            min: 0
        }, 
    status: {
            type: String,
    // 设置字符串的可选值
            enum: ['0', '1', '2']
        },
     phone: {
            type: Number,
            match: /^d{11}$/
        },
        desc: {
            type: String, maxlength: 20, minlength: 10
        }
    });
    
    

    Mongoose 自定义的验证器

    var UserSchema = new mongoose.Schema({
            name: {
                type: String, required: true,
            },
     age: {
                type: Number,
    // 是否必须的校验器
                required: true,
    // 数字类型的最大值校验器
                max: 120,
    // 数字类型的最小值校验器
                min: 0
            }, 
    status: {
                type: String,
    // 设置字符串的可选值
                enum: ['0', '1', '2']
            }, 
    phone: {
                type: Number,
                match: /^d{11}$/
            },
            desc: {
                type: String,
    // 自定义的验证器,如果通过验证返回 true,没有通过则返回 false
                validate: function (desc) {
                    return desc.length >= 10;
                }
            }
        });
    
    
  • 相关阅读:
    大牛都是这样写测试用例的,你get到了嘛?
    炸!分享美团面试关于selenium的面试题
    功能测试如何快速转向自动化测试?
    接口测试之深入理解HTTPS
    Linux之用户和权限
    Hash函数及其应用
    用代码控制网络断开与重连
    Windows Azure初体验
    JS跨域知识整理
    最大子序列和问题
  • 原文地址:https://www.cnblogs.com/bitlei/p/14436851.html
Copyright © 2011-2022 走看看