1.数据库概述及环境搭建
1.1 为什么要使用数据库
动态网站中的数据都是存储在数据库中的
数据库可以用来持久存储客户端通过表单收集的用户信息
数据库软件本身可以对数据进行高效的管理
http://www.czxy.com/article?id=1
http://www.czxy.com/article?id=2
1.2 什么是数据库
数据库即存储数据的仓库,可以将数据进行有序的分门别类的存储。它是独立于语言之外的软件,可以通过API去操作它。
常见的数据库软件有:mysql、mongoDB、oracle。
1.3MongoDB数据库下载安装
下载地址:https://www.mongodb.com/download-center/community
1.4 MongoDB可视化软件
MongoDB可视化操作软件,是使用图形界面操作数据库的一种方式。
1.5 数据库相关概念
在一个数据库软件中可以包含多个数据仓库,在每个数据仓库中可以包含多个数据集合,每个数据集合中可以包含多条文档(具体的数据)。
1.6 Mongoose第三方包
使用Node.js操作MongoDB数据库需要依赖Node.js第三方包mongoose
使用npm install mongoose命令下载
1.7 启动MongoDB
在命令行工具中运行net start mongoDB即可启动MongoDB,否则MongoDB将无法连接。
1.8 数据库连接
使用mongoose提供的connect方法即可连接数据库。
mongoose.connect('mongodb://localhost/playground')
.then(() => console.log('数据库连接成功'))
.catch(err => console.log('数据库连接失败', err));
- 1
- 2
- 3
1.9 创建数据库
在MongoDB中不需要显式创建数据库,如果正在使用的数据库不存在,MongoDB会自动创建。
2.MongoDB增删改查操作
2.1 创建集合
创建集合分为两步,一是对对集合设定规则,二是创建集合,创建mongoose.Schema构造函数的实例即可创建集合。
// 设定集合规则
const courseSchema = new mongoose.Schema({
name: String,
author: String,
isPublished: Boolean
});
// 创建集合并应用规则
const Course = mongoose.model('Course', courseSchema); // courses
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
2.3 创建文档
创建文档实际上就是向集合中插入数据。
分为两步:
创建集合实例。
调用实例对象下的save方法将数据保存到数据库中。
// 创建集合实例
const course = new Course({
name: 'Node.js course',
author: '黑马讲师',
tags: ['node', 'backend'],
isPublished: true
});
// 将数据保存到数据库中
course.save();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
Course.create({name: 'JavaScript基础', author: '黑马讲师', isPublish: true}, (err, doc) => {
// 错误对象
console.log(err)
// 当前插入的文档
console.log(doc)
});
Course.create({name: ‘JavaScript基础’, author: ‘黑马讲师’, isPublish: true})
.then(doc => console.log(doc))
.catch(err => console.log(err))
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
2.4 查询文档
// 根据条件查找文档
Course.findOne({name: 'node.js基础'}).then(result => console.log(result))
// 返回文档
{
_id: 5c0917ed27ec9b02c07cf95f,
name: 'node.js基础',
author: '黑马讲师‘
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
2.5 删除文档
// 删除单个
Course.findOneAndDelete({}).then(result => console.log(result))
// 删除多个
User.deleteMany({}).then(result => console.log(result))
- 1
- 2
- 3
- 4
- 5
2.6 更新文档
// 更新单个
User.updateOne({查询条件}, {要修改的值}).then(result => console.log(result))
// 更新多个
User.updateMany({查询条件}, {要更改的值}).then(result => console.log(result))
- 1
- 2
- 3
- 4
在创建集合规则时,可以设置当前字段的验证规则,验证失败就则输入插入失败。
required: true 必传字段
minlength:2 字符串最小长度
maxlength: 20 字符串最大长度
min: 2 数值最小为2
max: 100 数值最大为100
enum: [‘html’, ‘css’, ‘javascript’, ‘node.js’]
trim: true 去除字符串两边的空格
validate: 自定义验证器
default: 默认值
获取错误信息:error.errors[‘字段名称’].message
2.7 集合关联
通常不同集合的数据之间是有关系的,例如文章信息和用户信息存储在不同集合中,但文章是某个用户发表的,要查询文章的所有信息包括发表用户,就需要用到集合关联。
使用id对集合进行关联
使用populate方法进行关联集合查询
2.8 集合关联实现
// 用户集合
const User = mongoose.model('User', new mongoose.Schema({ name: { type: String } }));
// 文章集合
const Post = mongoose.model('Post', new mongoose.Schema({
title: { type: String },
// 使用ID将文章集合和作者集合进行关联
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}));
//联合查询
Post.find()
.populate('author')
.then((err, result) => console.log(result));
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
</div>
<link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-b6c3c6d139.css" rel="stylesheet">
<div class="more-toolbox">
<div class="left-toolbox">
<ul class="toolbox-list">
<li class="tool-item tool-active is-like "><a href="javascript:;"><svg class="icon" aria-hidden="true">
<use xlink:href="#csdnc-thumbsup"></use>
</svg><span class="name">点赞</span>
<span class="count"></span>
</a></li>
<li class="tool-item tool-active is-collection "><a href="javascript:;" data-report-click="{"mod":"popu_824"}"><svg class="icon" aria-hidden="true">
<use xlink:href="#icon-csdnc-Collection-G"></use>
</svg><span class="name">收藏</span></a></li>
<li class="tool-item tool-active is-share"><a href="javascript:;" data-report-click="{"mod":"1582594662_002"}"><svg class="icon" aria-hidden="true">
<use xlink:href="#icon-csdnc-fenxiang"></use>
</svg>分享</a></li>
<!--打赏开始-->
<!--打赏结束-->
<li class="tool-item tool-more">
<a>
<svg t="1575545411852" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5717" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M179.176 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5718"></path><path d="M509.684 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5719"></path><path d="M846.175 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5720"></path></svg>
</a>
<ul class="more-box">
<li class="item"><a class="article-report">文章举报</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div class="person-messagebox">
<div class="left-message"><a href="https://blog.csdn.net/xie_qi_chao">
<img src="https://profile.csdnimg.cn/B/F/6/3_xie_qi_chao" class="avatar_pic" username="xie_qi_chao">
<img src="https://g.csdnimg.cn/static/user-reg-year/1x/2.png" class="user-years">
</a></div>
<div class="middle-message">
<div class="title"><span class="tit"><a href="https://blog.csdn.net/xie_qi_chao" data-report-click="{"mod":"popu_379"}" target="_blank">解启超</a></span>
</div>
<div class="text"><span>发布了317 篇原创文章</span> · <span>获赞 48</span> · <span>访问量 3万+</span></div>
</div>
<div class="right-message">
<a href="https://im.csdn.net/im/main.html?userName=xie_qi_chao" target="_blank" class="btn btn-sm btn-red-hollow bt-button personal-letter">私信
</a>
<a class="btn btn-sm attented bt-button personal-watch" data-report-click="{"mod":"popu_379"}">已关注</a>
</div>
</div>
</div>
</article>