mongoDB 数据库

1. 什么是数据库
	数据库:存储数据的仓库,可以将数据进行有序的分类别的存储。它是独立于语言之外的软件,可以通过 API 去操作它。
    常见的数据库软件有:mysql, mongoDB, oracle
2. mongoDB 数据库下载安装
下载地址:https://www.mongodb.com/download-center/community
3. mongoDB 可视化软件
MongoDB可视化操作软件,是使用图形界面操作数据库的一种方式。
4. 数据库相关概念
   在一个数据库软件中可以包含多个数据仓库,在每个数据仓库中可以包含多个数据集合,每个数据集合中可以多条文档。
    databases  -->  数据库, mongoDB数据库软件可以创建多个数据库
    collection -->  集合, 一组数据的集合, 可以理解为 javascript中的数组
    document   -->  文档, 一条具体的数据,可以理解为javascript 中的对象
    field      -->  字段, 文档中的属性名称, 可以理解为javascript中的对象属性
5. 启动 mongoDB 数据库
net start mongodb // 启动数据库
net stop  mongodb  // 停止数据库 
6. 使用mongoose提供的 connect 方法连接 mongoDB数据库
// 1. 安装 mongoose 依赖
	npm install mongoose --save
// 2. 引入依赖
 	const mongoose = require('mongoose')
// 3.连接数据库 // mongoose.connect('mongoDB:://主机名: 端口/集合名称') 端口省略(27017)
 	// 在mongoDB中不需要显式创建数据库,如果正在使用的数据库不存在,mongoDB会自动创建
 	mongoose.connect('mongoDB:://localhost/studentInfo', {useNewUrlParser:true})
        .then(() => {
        	console.log('数据库连接成功。')
        }).catch(err => {
            console.log('数据库连接失败。')
        }) 
// 4. 设定集合规则 new mongoose.Scema(规则对象)
const studentSchema = new mongoose.Schema({
    name: String,
    age: Number,
    love: [Sting],
    isChecked: Boolean
})
// 5. 创建集合并应用规则 mongoose.modle(集合名称, 规则名称)  集合名称要大写
const Student = mongoose.modle('Student', studentSchema)  // Student 首字母必须大写
// 6. 通过 new 添加数据
const student = new Student({
    name: "王曦",
    age: 25,
    love: ['爬山', '乒乓球'],
    ischecked: false
})
// 7. 把数据保存数据库中
student.save()
6.1 创建集合
// 创建集合分为两步, 一是对对集合设定规则,二是创建集合, 创建 mongoose.model构造函数的实例即可创建集合。
// 1. 设定集合规则
const studentSchema = new mongoose.schema({
    name: Stirng,
    age: Number,
    address: String
})
// 2. 创建集合并应用规则
const Student = mongoose.modle('Student', studentSchema)

6.2.向mongoDB添加数据
// 方法一
const studentSchema = new mongoose.Schema({
    name: String,
    age: Number,
    isShow: Boolean
})
const Student = mongoose.model('Student', studentSchema)
const student = new Student({
    name: "王欣",
    age: 25,
    isShow: true
})
student.save()

// 方法二
const studentSchema = new mongoose.Schema({
    name: String,
    age: Number,
    isShow: Boolean
})
const Student = mongoose.model('Student', studentSchema)
Student.create({
    name: "王欣",
    age: 25,
    isShow: false
}, (err, data) => {
    // err 代表错误对象
    // data 代表插入的对象
    console.log(data)
})
// mongoDB 支持 promise 另一种写法
Student.create(插入的对象数据).then(data => {}).catch(err => {})

6.3 mongoDB 数据库导入数据
// mongoimport -d 数据库名称 -c 集合名称 --file 要导入的文件地址
mongoimport -d student -c user --file ./user.json
7. 从数据库中查找数据
// 1. find() 返回所有符合条件的集合
// 根据条件查找文档 (条件为空时,查找所有文档)
Student.find({}).then(result => {console.log(result)})
// 返回文档所有集合
[{
    name: '王欣',
    age: 25,
    isShow: false
}, {
    name: "李明轩",
    age: 26,
    isShow: true
}]

// 根据条件查找文档(条件不为空)
// 通过_id字段查找文档,返回符合条件的所有集合
Students.find({_id: "ef3dds32"}).then(result => {console.log(result)})

// 2.findOne() 方法返回一条文档,默认返回当前集合中的第一条文档。
Student.findOne({条件}).then(result => {console.log(result)})
// 完整实例
const mongoose = require('mongoose')
mongoose.connect("mongodb://localhost/student")
		.then(() => {
    		console.log("数据库连接成功!")
		})
		.catch(() => {
    		console.log("数据库连接失败!")
		})
const studentSchema = new mongoose.Schema({
    name: String,
    age: Number,
    address: String,
    hobbies: [String]
})
const Student = mongoose.model("Student", studentSchame)
Student.find({name: '李希'}).then((result) => {
    console.log(result)
})
7.1 文档查询
// 1.匹配大于($gt)、小于($lt)
// 查询年龄大于20, 小于50所有集合
Student.find({age: {$gt:20, $lt: 50}}).then(result => {console.log(result)})

// 2.匹配包含
// 查询包含设置的字段
Student.find({hobbies: {$in:['跳舞']}}).then(result => {console.log(result)})

// 3.设定要查询的字段
// 查询只包含设置的字段
Student.find().select('name', 'age').then(result => {console.log(result)})

// 4.将数据按照指定的字段,进行排序 sort() 升序排列
Student.find().sort('age').then(result => {console.log(result)}) // 升序
Student.find().sort('-age').then(result => {console.log(result)}) // 降序
8. 从数据库中删除数据
// 1.删除一个数据 findOneAndDelete(), 返回值是删除的数据
Student.findOneAndDelete({}).then(result => {console.log(result)})
// 查找到一条文档并且删除, 返回删除的文档
// 如果查询条件匹配了多个文档,那么将会删除第一个匹配的文档
Student.findOneAndDelete({_id:"fewadfwer2421faf"}).then(result => {console.log(result)})

// 2.删除多条数据 deleteMany(), 返回所有删除的数据
Student.deleteMany({}).then(result => {console.log(result)})
9. 更新数据库中的数据
// 1.更新一条数据
Student.updateOne({查询条件}, {要修改的值}).then(result => {console.log(result)})
// 更新集合中的文档(更新一个)
Student.undateOne({name: '李希'}, {name: '王曦'}).then(result => {console.log(result)})

// 2.更新多条数据
Student.updateMany({查询条件}, {要修改的值}).then(result => {console.log(result)})
// 更新集合中的文档(更新多个)
Student.updateMany({}, {age: 56}).then(result => {console.log(result)})
10 monogose 字段验证
// 在创建集合规则时, 可以设置当前字段的验证规则,验证失败则输入插入失败
1. require: true // 必传字段
2. minlength: 3 // 字符串最小长度
3. maxlength: 20 // 字符串最大长度
4. min: 2 // 数值最小值
5. max: 100 // 数值最大值
6. trim: true // 去除字符串首和尾的空格
7. default // 设置默认值
8. enum: ['html', 'css', 'node'] // 枚举
9. validate: { // 自定义验证规则, v 代表要验证的值
   		validator: v => {
        } 
   } //
mongoose.connect("mongodb://localhost/student", {useNewUrlParser: true})
		.then(() => { console.log("数据库连接成功!") })
		。catch(() => { console.log("数据库连接失败!") })

const studentSchema = new mongoose.Schema({
	name: {
		type: String,
		require: [true, '请输入名字'], // 第一个参数表示必传项, 第二参数表示失败时,返回值。
		minlength: 2,
		maxlength: 10
	},
    title: {
        type: String,
        require: [true, '请输入文章标题'],
        minlength: [2, '标题的长度不能小于2'],
        maxlength: [20, '标题的长度不能大于20'],
        trim: true //去除字符串两边的空格
    },
    publiceDate: {
        type: Date,
        default: Date.now // 设置默认值
    },
    category: {
        type: String,
        enum: {
            value: ['html', 'css', 'javascript', 'node'], // 枚举,列举出当前字段可以拥有的值
            message: "分类名称要在一定的范围内才可以。"
        } 
    },
    author: {
        type: String,
        validate: {
            validator: v => {
                return v && v.length > 4
            }
        },
        // 自定义错误信息
        message: "传入的值不符合验证规则"
    }
})

const Student = mongoose.model('Student', studentSchema)

Student.create({ name: '王欣' }).then((result) => { console.log(result) })
3.7 集合关联
	// 通常不同集合的数据之间是有关系的, 例如文章信息和用户信息存储在不同集合中, 但文章是某个用户发表的,要查询文章的所有信息包括发表用户,就需要用到集合关联。
	// 1. 使用 id 对集合进行关联
    // 2. 使用 populate 方法进行关联集合查询  
// 用户集合
const User = mongoose.model('User', new mongoose.schema({
    name: {
        type: String
    }
}))

// 文章集合
const Post = mongoose.model('Post', new mongoose.shema({
    title: {
        type: String,
    author: {
        type: mongoose.Schema.Types.ObjectId, // 绑定集合 User 的 ID
        ref: 'User
      }
    }
}))

// 添加数据
// 创建用户集合
// User.create({name: '王宇'}).then((result) => {console.log(result)})
//创建文章集合
// Post.create({title: 'node高级', author: User集合关联id号}).then(result => { console.log(result) })

// 联合查询
Post.find().populate('author').then((err, result) => { console.log(result) })
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值