连接数据库

113 阅读4分钟
  • 拿到解决跨域后的文件连接数据库
  • 前端文件夹建立js文件

连接数据库

 *    需要借助一个第三方包,mongoose,  安装命令:npm i mongoose
 *      下载  导入  按照说明文档使用

1.和数据库建立连接

//mongoose.connect('数据库地址','回调函数,连接成功后触发')

mongoose.connect('mongodb://localhost:27017/test2218',() => {
  /**
   * mongodb://localhost:27017/test2218'
   *  数据库默认地址mongodb://localhost:27017
   * 
   *    /test2218是我们进入到数据库的这个路径内,如果有直接进入,如果没有这个路径,那么会创建一个出来,然后进去到这个路径内
  */
  console.log('数据库连接成功')
})

2.创建一个遥控器.这个遥控器可以帮助我们简单的实现增删改查

/**
 * 创建一个表模型(创建的内容是表头)
*/
const Users = new mongoose.Schema({
  nickname:String,  //表示该表里有一个字段叫做nickname,类型为字符串类型
  age:Number,  //类型为数字类型
  username: {
    type: String,
    default: '用户账号',  //类型为字符串类型,有一个默认值为default
  },
  createTime: {
    type: Date,
    default: new Date() //类型为时间类型,有一个默认值
  },
  password: {
    type: String,
    require: true,  //类型为字符串类型,当前项为必填项
  },
  hobby: Array,  //类型为数组类型
  gender: {
    type: String,
    enum:['男','女','保密'] //类型为字符串类型,但是值只能从当前数组中出现
  }

})

/**
 * 利用表模型,创建我们需要的遥控器
 * 
*/

// const UsersModel = mongoose.model('表名','需要使用的表模型(就是表头)') 
const UsersModel = mongoose.model('users',Users)

3.利用刚才创建的遥控器进行增删改查

3.1增加(存储一条数据)

  • 语法: new 遥控器({你要存储的内容}).save()

  • 当前方法其实也是基于promise书写的一个方法

new UsersModel({
  nickname:'超级管理员',
  age:18,
  username:'admin',
  password:'123456',
  hobby:['足球','篮球'],
  gender:'保密'
}).save().then((res) => {
  console.log('当前数据保存成功',res)
}).catch((err) => {
  console.log('当前数据保存失败',err)
  
})

0.建立新数据库全部代码

const mongoose = require('mongoose')
mongoose.connect("mongodb://localhost:27017/test2218", () => {
    
    console.log("数据库连接成功");
});


// const Users = new mongoose.Schema('传递一些数据内容')


const Users = new mongoose.Schema({
    nickname: String, // 表示该 表 里, 有一个字段叫做 nickname, 类型为 字符串类型
    age: Number, // 类型为 数字类型
    username: {
        type: String,
        default: "用户账号", // 类型为 字符串类型, 用一个默认值为 'default'
    },
    createTime: {
        type: Date,
        default: new Date(), // 类型为 时间类型, 有一个默认值
    },
    password: {
        type: String,
        require: true, // 类型为 字符串类型, 当前项为 必填项
    },
    hobby: Array, // 类型为 数组类型
    gender: {
        type: String,
        enum: ["男", "女", "保密"], // 类型为 字符串类型, 但是值只能从当前数组中出现
    },
});


// const UsersModel = mongoose.model('表名', '需要使用的表模型(就是表头)')
const UsersModel = mongoose.model("users", Users);
const fn = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;

const str1 = "赵钱孙李周吴郑王冯陈褚卫蒋沈韩杨朱秦尤许何吕施张孔曹严华金魏陶姜";
const str2 = "一二三四五六七八九十";
const str3 = ["男", "女", "保密"];

for (let i = 0; i < 1234; i++) {
    const info = {
        nickname:
            str1[fn(0, str1.length - 1)] +
            str2[fn(0, str2.length - 1)] +
            str2[fn(0, str2.length - 1)],
        age: fn(18, 35),
        password: fn(100000, 999999) + "",
        hobby: ["足球", "篮球"],
        gender: str3[fn(0, 2)],
    };
    new UsersModel(info).save().then((res) => console.log("存储数据成功"));
}

4.数据库的查询语法

4.1基础查询

  • 语法:遥控器.find()
  • 结果:查询该表内所有的数据,以数组的形式返回
UsersModel.find().then((res) => {
  console.log(res)
})

4.2条件查询

  • 语法:遥控器.find({条件})
  • 结果:查询该表内所有的符合条件的数据
UsersModel.find({
  age:20
}).then((res) => {
  console.log(res)
})
UsersModel.find({
  age:{
    $gt:20,  //大于20
  }
}).then((res) => {
  console.log(res)
})


```js
UsersModel.find({
  age:{
    $lt:20,  //小于20
  }
}).then((res) => {
  console.log(res)
})
UsersModel.find({
  age:{
    $gt:20,  
    $lt:23
  }
}).then((res) => {
  console.log(res)
})
UsersModel.find({
  password:487837
}).then((res) => {
  console.log(res)
})

4.3分页查询

  • 语法:遥控器.find().skip(0).limit(5)

  • 返回值:0-5页

      * skip()跳过几条
      * limit()限制几条
    
UsersModel.find().skip(0).limit(5).then((res) => {
  console.log(res)
}) 

4.4根据ID查询

  • 语法:遥控器.findById()
  • 返回值:符合此ID的数据
UsersModel.findById('63f03d1b6cbf86757e9f03f9').then(res => console.log(res))

5.数据库的修改

5.1修改单一数据

UsersModel.updateOne(
  {age:34},   //找到age为20的第一个数据
  {nickname:'QF001'}
).then((res) => console.log(res))

5.2批量修改数据

UsersModel.updateMany(
  {age:18},   //找到age为20的第一个数据
  {nickname:'QF999'}
).then((res) => console.log(res))
//批量修改后检查是否成功
UsersModel.find({
  age:18
}).then((res) => console.log(res))

6,数据库的删除(了解即可)

6.1删除一个数据

UsersModel.deleteOne({
  age:34
}).then((res) => console.log(res))

6.2删除多个数据

UsersModel.deleteMany({
  age:34
}).then((res) => console.log(res))

// //批量删除后检查是否成功
UsersModel.find({
  age:34
}).then((res) => console.log(res))