MongoDB数据库的基本使用

1. 数据库概述及环境搭建

1.1 数据库相关概念

        在一个数据库软件中可以包含多个数据仓库,在每个数据仓库中可以包含多个数据集合,每个数据集合中可以包含多条文档((具体的数据)。

 

1.2 Mongoose第三方包

  • Node.js操作MongoDB数据库需要依赖Node.js第三方包mongoose
  • npm install mongoose命令下载

1.3 启动MongoDB

在命令行工具中运行net start mongoDB即可启动MongoDB,否则MongoDB将无法连接。

启动MongoDB发现错误:

进入C:\Windows\System32找到cmd.exe以管理员身份打开

1.4 数据库连接

//1.导入模块
const mongoose = require('mongoose')
//2.连接数据库
mongoose.connect("mongodb://localhost/vivo", { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('数据库连接成功'))
  .catch(err => console.log(err, '数据库连接失败'))

1.5 创建数据库

在MongoDB中不需要显式创建数据库,如果正在使用的数据库不存在,MongoDB会自动创建。

2. 使用图形化界面MongoDB数据库

3. MongoDB增删改查操作

3.1 创建集合

  • 对集合设定规则
  • 创建集合(创建mongoose.Schema构造函数的实例即可创建集合)
//1.导入模块
const mongoose = require('mongoose')
//2.连接数据库
mongoose.connect("mongodb://localhost/vivo", { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('数据库连接成功'))
  .catch(err => console.log(err, '数据库连接失败'))
//3.创建集合规则
const bannerSchema = new mongoose.Schema({
  img:String
})
//4.创建集合并应用规则
//真实的集合名字是Banner
const Banner = mongoose.model('Banner',bannerSchema)

3.2 创建文档

创建文档实际上就是向集合中插入数据。

分为两步:

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

方法一:

//5.创建集合实例(文档)
const banner = new Banner({
  img: 'hh'
})
//6.将文档数据保存到数据库中
banner.save()

方法二:

//5.向集合插入文档
Banner.create({ img: 'hehe' }, (err, result) => {
  console.log(err);
  console.log(result);
})

数据库的操作都是异步的,所以可以用promise方法

//5.向集合插入文档
Banner.create({ img: 'qq' })
  .then(result => {
    console.log(result)
  })
  .catch(err => {
    console.log(err)
  })

3.3 mongoDB数据库导入数据

mongoimport  -d 数据库名称 -c 集合名称 --file 要导入的数据文件

找到mongodb数据库的安装目录,将安装目录下的bin目录放置在环境变量中。

3.4 查询文档

3.4.1 查询所有文档

//查询所有文档
Banner.find().then((result) => {
  console.log(result)
})

以数组形式返回

3.4.2 根据条件查询文档

//根据条件查询文档
Banner.find({
  img: 'hh'
}).then((result) => {
  console.log(result)
})

以数组形式返回

3.4.3 查询一条数据

没有查询条件默认返回第一条,以对象形式返回

Banner.findOne({
  img: 'hh'
}).then((result) => {
  console.log(result)
})

3.4.4 查询匹配条件的数据

//匹配大于  小于
//找到年龄大于20小于40的文档
User.find({
  age: { $gt: 20, $lt: 40 }
}).then((result) => {
  console.log(result)
})
//匹配包含
//找爱好包含足球的
User.find({
  hobbies: { $in: ['足球'] }
}).then((result) => {
  console.log(result)
})

 

3.4.5 查询匹配字段

//id字段默认会查询
User.find().select('name phone').then((result) => {
  console.log(result)
})
//不想查询id字段,在_id前面加个-
User.find().select('name phone -_id').then((result) => {
  console.log(result)
})

3.4.6 对查询的数据结果进行排序

//根据年龄字段进行升序排列
User.find().sort('age').then((result) => {
  console.log(result)
})
//根据年龄字段进行降序排列
User.find().sort('-age').then((result) => {
  console.log(result)
})

3.4.7 跳过查询和限制数量查询(可用于分页功能)

//skip跳过多少条数据,limit限制查询数量
User.find().skip(2).limit(2).then((result) => {
  console.log(result)
})

3.5 删除文档

//删除单个文档
//返回删除的文档
//如何查询条件匹配了多个文档那么将会删除第一个匹配的文档
Banner.findOneAndDelete({
  _id: '61148677713eee52d8feba92'
}).then((result) => {
  console.log(result)
})
//删除多个文档
//不写查询条件会删除全部文档
//返回  { n: 2,ok: 1, deletedCount: 2 }  
Banner.deleteMany({}).then((result) => {
  console.log(result)
})

3.6 更新文档

//更新单个文档
//User.updateOne({查询条件},{要修改的值}) .then(result => console.log(result))
Banner.updateOne({ img: 'qq' }, { img: 'wechat' }).then(result => console.log(result))
//更新多个文档
Banner.updateMany({}, { img: 'hh' }).then(result => console.log(result))

3.7 mongoose验证

在创建集合规则时,可以设置当前字段的验证规则,验证失败就则输入插入失败。

  • required: true 必传字段
  • minlength 字符串最小长度
  • maxlength 字符串最大长度
  • trim:true 去除字符串两边的空格
  • min 数值的最小值
  • max 数值的最大值
  • default 默认值
  • enum 枚举,列出当前字段可以使用的值

 

//创建集合规则
//const bannerSchema = new mongoose.Schema({
//  img: {
//    type: String,
//    required: true
//  }
//})
const bannerSchema = new mongoose.Schema({
  img: {
    type: String,
    required: [true, '请传入图片地址'],//自定义错误提示信息
    minlength: 2,
    maxlength: 5,
    trim: true
  },
  age: {
    type: Number,
    min: 0,
    max: 150
  },
  publishDate: {
    type: Date,
    default: Date.now
  },
  category: {
    type: String,
    enum: ['html', 'css', 'javascript']
  },
  author: {
    type: String,
    validate: {
        //返回布尔值
      validator: v => v && v.length > 4
    },
    //自定义错误信息
    message: '传入的值不符合验证规则'
  }
})
//创建集合应用规则
const Banner = mongoose.model('Banner', bannerSchema)
//插入文档
//会报错,因为img是必传字段,这里没有传
Banner.create({})
  .then(result => {
    console.log(result)
  })
  .catch(err => {
    console.log(err)
  })

拿到错误信息:

//插入文档
Banner.create({
  img: 'ccccc',
  age: 18,
  category: 'htmlsfe',
  author: 'zsysfwe'
})
  .then(result => {
    console.log(result)
  })
  .catch(err => {
    console.log(err)
  })

错误太长,我们可以拿到自己自定义的错误信息:

//插入文档
Banner.create({
  img: 'ccccc',
  age: 18,
  category: 'htmlsfe',
  author: 'zsy'
})
  .then(result => {
    console.log(result)
  })
  .catch(err => {
      //获取错误信息对象
    const error = err.errors
    for (var attr in error) {
      console.log(error[attr]['message'])
    }
  })

 

3.7集合关联

        通常不同集合的数据之间是有关系的,例如文章信息和用户信息存储在不同集合中,但文章是某个用户发表的,要查询文章的所有信息包括发表用户,就需要用到集合关联。

  • id对集合进行关联
  • populate方法进行关联集合查询

//创建用户集合规则
const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  }
})
//创建文章集合规则
const postSchema = new mongoose.Schema({
  title: {
    type: String
  },
  author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }
})
//创建用户集合应用规则
const User = mongoose.model('User', userSchema)
//创建文章集合应用规则
const Post = mongoose.model('Post', postSchema)
//创建用户文档
// User.create({ name: 'hh' }).then(result => console.log(result))
//创建文章文档
// Post.create({ title: 'heihei', author: '6114d911f372ae5944ac9ea3' })
//   .then(result => console.log(result))
//查询数据
Post.find().populate('author').then(result => console.log(result))

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值