• MongoDB数据库使用API


    [备忘使用]

    启动MongoDB

    net start mongoDB
    
    net stop mongoDB
    

    连接数据库

    mongoose.connetc('mongodb://localhost/playground').then( () => console.log('数据库连接成功')).catch( err => {console.log('数据库连接失败!')})
    

    在MongoDB中如果使用的数据库不存在,就会被创建!

    创建集合

    • 对集合设定规则

    • 创建集合

      // 设定集合规则
      const courseSchema = new mongoose.Schema({
          name: String,
          author: String,
          isPubulished: Boolean
      })
      // 创建集合并应用规则
      const Course = mongoose.model('Course', courseSchema)
      

    插入数据

    • 创建集合实例

    • 调用实例对象下的save方法将数据保存到数据库中

      // 创建文档实例
      const course = new Course({
          name: 'Node js ',
          tags: ['node', 'test'],
          isPublished: true
      })
      // 保存文档实例
      course.save()
      
    • create方法

      Course.create({
          name: 'kangkang',
          age: 19,
          isPublish: true
      }, (err,doc) => {
          if(err) {
              console.log(err) 
              return
          }
          console.log(doc)
      })
      
      
      Course.create({
          name: 'kangkang',
          age: 19,
          isPublish: true
      }).then(doc => {}).catch(err => {console.log(err)})
      

    查询数据

    如何将数据导入数据库中

    // -d 代表数据库  -c 导入哪个集合中 -file 要导入的文件
    mongoimport -d 数据库名称 -c 集合名称 --file 要导入的数据文件
    
    // 返回文档的集合
    Course.find().then(result => console.log(result))
    

    精确查找

    • find

    • findOne 没有条件返回当前集合的第一个

    模糊查找

    // $gt 大于 $lt小于
    City.find({age: {$gt: 20, $lt: 50}}).then(result => {console.log(result)})
    
    // 包含
    City.find({citys: {$in:['足球']}}).then(result => {console.log(result)})
    
    // 选择需要查询的字段 -_id表示去除_id字段
    City.find().select('name age -_id').then(result => {console.log(result)})
    
    // 将数据按照某个字段进行排序(升序)
    City.find().sort('name').then(result => {console.log(result)})
    // 将数据按照某个字段进行排序(降序)
    City.find().sort('-name').then(result => {console.log(result)})
    
    // skip跳过多少条,limt限制多少条数 (分页)
    City.find().skip(2).limt(2).then(result =>{console.log(result)})
    

    删除文档

    // 删除单个,查找第一个并删除
    City.findOneAndDelete({}).then(result =>{console.log(result)})
    
    // 删除多个
    City.deleteMany({}).then(result =>{
        // 一个对象{n:2, Ok: 1} ok-1删除成功,n是删除的个数
        console.log(result)
    })
    

    更新文档

    // 更新单个
    City.updateOne({查询条件}, {要修改的值}).then(result => {
        console.log(result)
    })
    
    // 实例
    user.updateOne({ username: 'daixixi' }, { age: 28 }).then(doc => {
      console.log(doc);
      const { n, nModified, ok } = doc;
      console.log(`更新了${nModified}个数据`);
    }).catch(err => {
      console.log('更新失败~!', err);
    });
    
    // 更新多个
    City.updateMany({查询条件}, {要更改的值}).then(result => {
        console.log(result)
    })
    
    // 实例
    user.updateMany({}, { age: 88 }).then(doc => {
      console.log(doc);
      const { n, nModified, ok } = doc;
      console.log(`总计查询到${n}个数据,更新了${nModified}个数据`);
    }).catch(err => {
      console.log('更新失败~!', err);
    });
    

    mongoose验证

    创建集合的时候可以设置当前字段的验证规则,验证失败则插入失败!

    • required: true 必传字段
    • maxLength
    • minLength
    • min
    • max
    // 创建schema
    const userSchema = new mongoose.Schema({
      username: String,
      city: String,
      age: Number,
        // 添加默认值
      birthday: {
        type: String,
        default: Date.now()
      },
        // 指定上传内容
      category: {
        type: String,
        enum: {
          values:  ['html', 'css', 'javascript', 'node.js'],
          message: '分类名称指定类型中'
        }
      },
      author: {
        type: String,
        validate: {
          // 接收一个布尔值,如果true则验证成功,如果是false则验证失败
          validator: v => {
            return v && v.length > 4;
          },
          // 自定义错误信息
          message: '传入值不符合验证规则'
        }
      }
    });
    
    // 会自动将默认值带上写入数据库
    user.create({ username: 'xiaoliang', city: 'xxx', age: 22 }).then(doc => {
      console.log('添加成功!');
    }).catch(err => {
      console.log(err);
    });
    
    

    数据内容的关联

    const userSchema = mongoose.Schema({
      user: {
        type: String
      }
    });
    
    
    const user = mongoose.model('user', userSchema, 'user');
    
    const authorSchema = mongoose.Schema({
      title: String,
      author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'user'
      }
    });
    
    const author = mongoose.model('author', authorSchema, 'author');
    
    
    // 创建用户
    // user.create({ usr: 'daixixi' }).then(doc => {
    //   console.log('用户登录成功~!');
    // }).catch(err => {
    //   console.log('添加失败', err);
    // });
    // 创建文章
    // author.create({ title: '人类的存亡和兴衰.txt', author: '5e22d03addc2ca46041b2788' }).then(doc => {
    //   console.log('添加文章成功~!');
    // }).catch(err => {
    //   console.log('添加失败~!', err);
    // });
    
    author.find().populate('author').then(res => {
      console.log(res);
    }).catch(err => {
      console.log(err);
    });
    
    
  • 相关阅读:
    Lua 随机数生成问题
    关于LUA中的随机数问题
    用setup.py安装第三方包packages
    问题解决 -------- 解决YUM下Loaded plugins: fastestmirror Determining fastest mirrors 的问题
    CentOS6.7上安装Mysql5.7
    Centos6.8通过yum安装mysql5.7
    Gcc ------ gcc的使用简介与命令行参数说明
    redis 常用命令
    redis学习系列
    C# Redis实战
  • 原文地址:https://www.cnblogs.com/daixixi/p/12208663.html
Copyright © 2020-2023  润新知