数据库概念和环境搭建
什么是数据库
数据库即存储数据的仓库,可以将数据进行有序的分门别类的存储。它是独立于语言之外的软件,可以通过API去操作它。
- 常见的数据库软件有:mysql、mongoDB、oracle。
MongoDB数据库下载安装
链接:https://pan.baidu.com/s/1Yikc-vgqCXmmWd1SDIshAw
提取码:eml6
复制这段内容后打开百度网盘手机App,操作更方便哦
MongoDB可视化软件
MongoDB可视化操作软件,是使用图形界面操作数据库的一种方式。
数据库相关概念
在一个数据库软件中可以包含多个数据仓库,在每个数据仓库中可以包含多个数据集合,每个数据集合中可以包含多条文档(具体的数据)。
Mongoose第三方包
使用Node.js操作MongoDB数据库需要依赖Node.js第三方包mongoose
使用npm install mongoose
命令下载
启动和关闭MongoDB
启动
net start mongoDB
关闭
net stop mongoDB
连接数据库 (★★★★★ )
使用mongoose提供的
connect
方法即可连接数据库。
//首先引入mongoose
const mongoose = require('mongoose')
//数据库地址/数据库名称
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('数据库连接成功'))
.catch(err => console.log('数据库连接失败', err));
创建数据库
在MongoDB中不需要显式创建数据库
,如果正在使用的数据库不存在,MongoDB会自动创建
。
MongoDB增删改查
创建集合
创建集合分为两步,
1.是对对集合设定规则
2.是创建集合
,创建mongoose.Schema({});构造函数的实例即可创建集合。
// 一、连接数据库
//首先引入mongoose
const mongoose = require('mongoose')
//数据库地址/数据库名称
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('数据库连接成功'))
.catch(err => console.log('数据库连接失败', err));
// 二、创建集合
//创建集合规则
const courseSchema = new mongoose.Schema({
name: String,
author: String,
isPublishhed: Boolean
})
// 使用规则创建集合
// 1.集合名称
// 2.集合规则
const Course = mongoose.model('Course', courseSchema);
//当前集合的构造函数
现在我们运行文件发现并没有发现有这个数据库
这是因为这里没有插入数据
创建文档 - 插入数据
创建文档实际上就是向集合中插入数据
。
分为两步:
- 创建集合实例。
- 调用实例对象下的save方法将数据保存到数据库中。
// 创建集合实例
const course = new Course({
name: 'Node.js course',
author: '123',
tags: ['a', 'b'],
isPublished: true
});
// 将数据保存到数据库中
course.save();
实际代码
// 一、连接数据库
//首先引入mongoose
const mongoose = require('mongoose')
//数据库地址/数据库名称
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('数据库连接成功'))
.catch(err => console.log('数据库连接失败', err));
// 二、创建集合
//创建集合规则
const courseSchema = new mongoose.Schema({
name: String,
author: String,
isPublishhed: Boolean
})
// 使用规则创建集合
// 1.集合名称
// 2.集合规则
const Course = mongoose.model('Course', courseSchema);
//当前集合的构造函数
// 三.插入数据
// 创建集合实例
const course = new Course({
name: 'Node.js',
author: 'zhangsan',
tags: ['node', 'course'],//没有在集合规则里定义tags 所以数据库没有这个属性
isPublished: true
});
// 调用 save方法 将数据保存到数据库中
course.save();
方法二 create()
集合实例名称.create({'要插入的文档对象'},(err,doc)=>{'回调函数'})
通过回调函数
Course.create({name: 'JavaScript', author: 'zhangsan', isPublish: true}, (err, doc) => {
// 错误对象
console.log(err)
// 当前插入的文档
console.log(doc)
});
通过Promis对象
Course.create({name: 'JavaScript', author: '张三', isPublish: true})
.then(doc => console.log(doc))
.catch(err => console.log(err))
mongoDB数据库导入数据
mongoimport –d 数据库名称 –c 集合名称 –file
要导入的数据文件
找到mongodb数据库的安装目录,将安装目录下的bin目录放置在环境变量中。
// .json文件
{"_id":{"$oid":"5c09f1e5aeb04b22f8460965"},"name":"张三","age":20,"hobbies":["足球","篮球","橄榄球"],"email":"zhangsan@itcast.cn","password":"123456"}
{"_id":{"$oid":"5c09f236aeb04b22f8460967"},"name":"李四","age":10,"hobbies":["足球","篮球"],"email":"lisi@itcast.cn","password":"654321"}
{"_id":{"$oid":"5c09f267aeb04b22f8460968"},"name":"王五","age":25,"hobbies":["敲代码"],"email":"wangwu@itcast.cn","password":"123456"}
{"_id":{"$oid":"5c09f294aeb04b22f8460969"},"name":"赵六","age":50,"hobbies":["吃饭","睡觉","打豆豆"],"email":"zhaoliu@itcast.cn","password":"123456"}
{"_id":{"$oid":"5c09f2b6aeb04b22f846096a"},"name":"王二麻子","age":32,"hobbies":["吃饭"],"email":"wangermazi@itcast.cn","password":"123456"}
{"_id":{"$oid":"5c09f2d9aeb04b22f846096b"},"name":"狗蛋","age":14,"hobbies":["打豆豆"],"email":"goudan@163.com","password":"123456"}
查询文档
// 根据条件查找文档(条件为空则查找所有文档)
Course.find().then(result => console.log(result))
// 返回文档集合
[{
_id: 5c0917ed37ec9b03c07cf95f,
name: 'node.js基础',
author: 'zhangsan'
},{
_id: 5c09dea28acfb814980ff827,
name: 'Javascript',
author: '李四'
}]
// 根据条件查找文档
//当没有条件时,返回的是对象 findOne默认返回的是数据库第一条数据
Course.findOne({name: 'node.js基础'}).then(result => console.log(result))
// 匹配大于$gt 小于$lt 固定写法
User.find({age: {$gt: 20, $lt: 50}}).then(result => console.log(result))
// 匹配包含 $in:['条件']
User.find({hobbies: {$in: ['敲代码']}}).then(result => console.log(result))
// 选择要查询的字段 .select('要查询的字段 多个字段要用空格 空开')
//如果有不想查询的字段 可以在该字段前加 - 比如下面的id字段
User.find().select('name email -id').then(result => console.log(result))
// 将数据按照年龄进行排序
//如果要降序 可以在字段前加 -
//升序
User.find().sort('age').then(result => console.log(result))
//降序
User.find().sort('-age').then(result => console.log(result))
// skip 跳过多少条数据 limit 限制查询数量 可以用来做分页功能
User.find().skip(2).limit(2).then(result => console.log(result))
实际代码
// 引入mongoose第三方模块 用来操作数据库
const mongoose = require('mongoose');
// 数据库连接
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true })
// 连接成功
.then(() => console.log('数据库连接成功'))
// 连接失败
.catch(err => console.log(err, '数据库连接失败'));
// 创建集合规则
const userSchema = new mongoose.Schema({
name: String,
age: Number,
email: String,
password: String,
hobbies: [String]
});
// 使用规则创建集合
const User = mongoose.model('User', userSchema);
// 查询用户集合中的所有文档
User.find().then(result => console.log(result));
// 通过_id字段查找文档
User.find({ _id: '5c09f267aeb04b22f8460968' }).then(result => console.log(result))
// findOne方法返回一条文档 默认返回当前集合中的第一条文档
User.findOne({ name: '李四' }).then(result => console.log(result))
// 查询用户集合中年龄字段大于20并且小于40的文档
User.find({ age: { $gt: 20, $lt: 40 } }).then(result => console.log(result))
// 查询用户集合中hobbies字段值包含足球的文档
User.find({ hobbies: { $in: ['足球'] } }).then(result => console.log(result))
// 选择要查询的字段
User.find().select('name email -_id').then(result => console.log(result))
// 根据年龄字段进行升序排列
User.find().sort('age').then(result => console.log(result))
// 根据年龄字段进行降序排列
User.find().sort('-age').then(result => console.log(result))
// 查询文档跳过前两条结果 限制显示3条结果
User.find().skip(2).limit(3).then(result => console.log(result))
删除文档
// 删除单个
Course.findOneAndDelete({查询条件}).then(result => console.log(result))
//返回的是删除的字段
// 删除多个
User.deleteMany({查询条件}).then(result => console.log(result))
//返回的是对象
{n:删除的文档数量,ok:1 是否成功}
实际代码
// 引入mongoose第三方模块 用来操作数据库
const mongoose = require('mongoose');
// 数据库连接
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true})
// 连接成功
.then(() => console.log('数据库连接成功'))
// 连接失败
.catch(err => console.log(err, '数据库连接失败'));
// 创建集合规则
const userSchema = new mongoose.Schema({
name: String,
age: Number,
email: String,
password: String,
hobbies: [String]
});
// 使用规则创建集合
const User = mongoose.model('User', userSchema);
// 查找到一条文档并且删除
// 返回删除的文档
// 如何查询条件匹配了多个文档 那么将会删除第一个匹配的文档
// User.findOneAndDelete({_id: '5c09f267aeb04b22f8460968'}).then(result => console.log(result))
// 删除多条文档
User.deleteMany({}).then(result => console.log(result))
更新文档
// 更新单个
User.updateOne({查询条件}, {要修改的值}).then(result => console.log(result))
// 更新多个
User.updateMany({查询条件}, {要更改的值}).then(result => console.log(result))
这里也会返回一个对象
{n:受影响的数据,nModified:修改的数据,ok:1 是否成功}
实际代码
// 引入mongoose第三方模块 用来操作数据库
const mongoose = require('mongoose');
// 数据库连接
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true})
// 连接成功
.then(() => console.log('数据库连接成功'))
// 连接失败
.catch(err => console.log(err, '数据库连接失败'));
// 创建集合规则
const userSchema = new mongoose.Schema({
name: String,
age: Number,
email: String,
password: String,
hobbies: [String]
});
// 使用规则创建集合
const User = mongoose.model('User', userSchema);
// 找到要删除的文档并且删除
// 返回是否删除成功的对象
// 如果匹配了多条文档, 只会删除匹配成功的第一条文档
User.updateOne({name: '李四'}, {age: 120, name: '李狗蛋'}).then(result => console.log(result))
// 找到要删除的文档并且删除
User.updateMany({}, {age: 300}).then(result => console.log(result))
mongoose验证
在创建集合规则时,可以设置当前字段的验证规则,验证失败就则输入插入失败。
required: true
必传字段required: [true,'自定义的信息'-用于查看报错信息]
下面的都可以minlength:3
字符串最小长度maxlength: 20
字符串最大长度min: 2
数值最小为2max: 100
数值最大为100enum: ['html', 'css', 'javascript', 'node.js']
: 规定字段trim: true
去除字符串两边的空格validate:
自定义验证器default:
默认值
获取错误信息:error.errors[‘字段名称’].message
实际代码
// 引入mongoose第三方模块 用来操作数据库
const mongoose = require('mongoose');
// 数据库连接
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true})
// 连接成功
.then(() => console.log('数据库连接成功'))
// 连接失败
.catch(err => console.log(err, '数据库连接失败'));
const postSchema = new mongoose.Schema({
title: {
type: String,
// 必选字段
required: [true, '请传入文章标题'],
// 字符串的最小长度
minlength: [2, '文章长度不能小于2'],
// 字符串的最大长度
maxlength: [5, '文章长度最大不能超过5'],
// 去除字符串两边的空格
trim: true
},
age: {
type: Number,
// 数字的最小范围
min: 18,
// 数字的最大范围
max: 100
},
publishDate: {
type: Date,
// 默认值
default: Date.now
},
category: {
type: String,
// 枚举 列举出当前字段可以拥有的值
enum: {
values: ['html', 'css', 'javascript', 'node.js'],
message: '分类名称要在一定的范围内才可以'
}
},
author: {
type: String,
validate: {
validator: v => {
// 返回布尔值
// true 验证成功
// false 验证失败
// v 要验证的值
return v && v.length > 4
},
// 自定义错误信息
message: '传入的值不符合验证规则'
}
}
});
const Post = mongoose.model('Post', postSchema);
Post.create({title:'aa', age: 60, category: 'java', author: 'bd'})
.then(result => console.log(result))
.catch(error => {
// 获取错误信息对象
const err = error.errors;
// 循环错误信息对象
for (var attr in err) {
// 将错误信息打印到控制台中
console.log(err[attr]['message']);
}
})
集合关联
通常
不同集合的数据之间是有关系的
,例如文章信息和用户信息存储在不同集合中,但文章是某个用户发表的,要查询文章的所有信息包括发表用户,就需要用到集合关联。
- 使用id对集合进行关联
- 使用populate方法进行关联集合查询
集合关联实现
// 用户集合
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));
案例
// 引入mongoose第三方模块 用来操作数据库
const mongoose = require('mongoose');
// 数据库连接
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true})
// 连接成功
.then(() => console.log('数据库连接成功'))
// 连接失败
.catch(err => console.log(err, '数据库连接失败'));
// 用户集合规则
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: 'itheima'}).then(result => console.log(result));
// 创建文章
// Post.create({title: '123', author: '5c0caae2c4e4081c28439791'}).then(result => console.log(result));
Post.find().populate('author').then(result => console.log(result))
案例:用户信息增删改查
// 搭建网站服务器,实现客户端与服务器端的通信
// 连接数据库,创建用户集合,向集合中插入文档
// 当用户访问/list时,将所有用户信息查询出来
// 实现路由功能
// 呈现用户列表页面
// 从数据库中查询用户信息 将用户信息展示在列表中
// 将用户信息和表格HTML进行拼接并将拼接结果响应回客户端
// 当用户访问/add时,呈现表单页面,并实现添加用户信息功能
// 当用户访问/modify时,呈现修改页面,并实现修改用户信息功能
// 修改用户信息分为两大步骤
// 1.增加页面路由 呈现页面
// 1.在点击修改按钮的时候 将用户ID传递到当前页面
// 2.从数据库中查询当前用户信息 将用户信息展示到页面中
// 2.实现用户修改功能
// 1.指定表单的提交地址以及请求方式
// 2.接受客户端传递过来的修改信息 找到用户 将用户信息更改为最新的
// 当用户访问/delete时,实现用户删除功能
链接:https://pan.baidu.com/s/1Hgxbm2IUHb5xWl7HKw8VxA
提取码:nm6j
复制这段内容后打开百度网盘手机App,操作更方便哦
这个案例用到了大量的字符串拼接html 下面我们要学习模块化进行修改
模板引擎artTemplate
基础概念
模块引擎
模板引擎是第三方模块。
让开发者以更加友好的方式拼接字符串,使项目代码更加清晰、更加易于维护。
// 未使用模板引擎的写法
var ary = [{ name: '张三', age: 20 }];
var str = '<ul>';
for (var i = 0; i < ary.length; i++) {
str += '<li>\
<span>'+ ary[i].name +'</span>\
<span>'+ ary[i].age +'</span>\
</li>';
}
str += '</ul>';
<!-- 使用模板引擎的写法 -->
<ul>
{{each ary}}
<li>{{$value.name}}</li>
<li>{{$value.age}}</li>
{{/each}}
</ul>
art-template模板引擎 安装使用
- 在命令行工具中使用
npm install art-template
命令进行下载 - 使用
const template = require('art-template')
引入模板引擎 - 告诉模板引擎要拼接的数据和模板在哪
const html = template(‘模板路径’, 数据);
- 使用模板语法告诉模板引擎,模板与数据应该如何进行拼接
// 导入模板引擎模块
const template = require('art-template');
// 将特定模板与特定数据进行拼接
const html = template('./views/index.art',{
data: {
name: '张三',
age: 20
}
});
//index.art
<div>
<span>{{data.name}}</span>
<span>{{data.age}}</span>
</div>
实际代码
//app.js
// 导入模板引擎
const template = require('art-template');
const path = require('path');
//拼接路径
const views = path.join(__dirname, 'views', 'index.art');
// template方法是用来拼接字符串的
// 1. 模板路径 绝对路径
// 2. 要在模板中显示的数据 对象类型
// 返回拼接好的字符串
const html = template(views, {
name: '张三',
age: 20
})
console.log(html);
//index.art
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
{{ name }}
{{ age }}
</body>
</html>
模块语法
art-template
同时支持两种模板语法:标准语法和原始语法。- 标准语法可以让模板更容易读写,原始语法具有强大的逻辑处理能力。
标准语法: {{ 数据 }}
原始语法:<%=数据 %>
输出内容
将某项数据输出在模板中,标准语法和原始语法如下:
- 标准语法:{{ 数据 }}
- 原始语法:<%=数据 %>
在语法中还可以进行,运算,判断
<!-- 标准语法 -->
<h2>{{value}}</h2>
<h2>{{a ? b : c}}</h2>
<h2>{{a + b}}</h2>
<!-- 原始语法 -->
<h2><%= value %></h2>
<h2><%= a ? b : c %></h2>
<h2><%= a + b %></h2>
原文输出
如果数据中携带HTML标签,默认模板引擎不会解析标签,会将其转义后输出。
标准语法:{{@ 数据 }} //@
原始语法:<%-数据 %> // -
<!-- 标准语法 -->
<h2>{{@ value }}</h2>
<!-- 原始语法 -->
<h2><%- value %></h2>
条件判断
<!-- 标准语法 -->
{{if 条件}} ... {{/if}}
{{if v1}} ... {{else if v2}} ... {{/if}}
<!-- 原始语法 -->
<% if (value) { %> ... <% } %>
<% if (v1) { %> ... <% } else if (v2) { %> ... <% } %>
{{if age > 18}}
年龄大于18
{{else if age < 15 }}
年龄小于15
{{else}}
年龄不符合要求
{{/if}}
<% if (age > 18) { %>
年龄大于18
<% } else if (age < 15) { %>
年龄小于15
<% } else { %>
年龄不符合要求
<% } %>
循环
标准语法:{{each 数据}} {{/each}}
原始语法:<% for() { %> <% } %>
<!-- 标准语法 -->
{{each target}}
{{$index}} {{$value}}
{{/each}}
<!-- 原始语法 -->
<% for(var i = 0; i < target.length; i++){ %>
<%= i %> <%= target[i] %>
<% } %>
实际代码
<ul>
{{each users}}
<li>
{{$value.name}}
{{$value.age}}
{{$value.sex}}
</li>
{{/each}}
</ul>
<ul>
<% for (var i = 0; i < users.length; i++) { %>
<li>
<%=users[i].name %>
<%=users[i].age %>
<%=users[i].sex %>
</li>
<% } %>
</ul>
子模板
使用子模板可以将网站公共区块(头部、底部)抽离到单独的文件中。
标准语法:{{include '模板'}}
原始语法:<%include('模板') %>
<!-- 标准语法 -->
{{include './header.art'}}
<!-- 原始语法 -->
<% include('./header.art') %>
代码案例
{{ include './common/header.art' }}
<% include('./common/header.art') %>
<div> {{ msg }} </div>
{{ include './common/footer.art' }}
<% include('./common/footer.art') %>
模板继承
使用模板继承可以将网站HTML骨架抽离到单独的文件中,其他页面模板可以继承骨架文件。
示例
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>HTML骨架模板</title>
{{block 'head'}}{{/block}}
</head>
<body>
{{block 'content'}}{{/block}}
</body>
</html>
<!--index.art 首页模板-->
{{extend './layout.art'}}
{{block 'head'}} <link rel="stylesheet" href="custom.css"> {{/block}}
{{block 'content'}} <p>This is just an awesome page.</p> {{/block}}
模板配置
- 向模板中导入变量
template.defaults.imports.变量名 = 变量值;
- 设置模板根目录
template.defaults.root = 模板目录
- 设置模板默认后缀
template.defaults.extname = '.art'
处理时间格式 dateformat插件
https://www.npmjs.com/package/dateformat
npm install dateformat
示例
const template = require('art-template');
const path = require('path');
const dateFormat = require('dateformat');
// 设置模板的根目录
template.defaults.root = path.join(__dirname, 'views');
// 导入模板变量
template.defaults.imports.dateFormat = dateFormat;
// 配置模板的默认后缀
template.defaults.extname = '.html';
//导入文件
const html = template('06.art', {
time: new Date()
});
console.log(template('07', {}));
console.log(html);
//06.art
{{ dateFormat(time, 'yyyy-mm-dd')}}
// 07
我是07.html模板
案例-学生档案管理
制作流程
第三方模块 router
功能:实现路由
安装
npm install router
使用步骤:
- 获取路由对象
- 调用路由对象提供的方法创建路由
- 启用路由,使路由生效
const getRouter = require('router')
const router = getRouter();
router.get('/add', (req, res) => {
res.end('Hello World!')
})
server.on('request', (req, res) => {
router(req, res)
})
第三方模块 serve-static
安装
npm install serve-static
功能:实现静态资源访问服务
步骤:
- 引入serve-static模块获取创建静态资源服务功能的方法
- 调用方法创建静态资源服务并指定静态资源服务目录
- 启用静态资源服务功能
const serveStatic = require('serve-static')
const serve = serveStatic('public')
server.on('request', () => {
serve(req, res)
})
server.listen(3000)
添加学生信息功能步骤分析
学生信息列表页面分析
链接:https://pan.baidu.com/s/1QqSRhuA9iI4qNIB8gXPG6w
提取码:m7om
复制这段内容后打开百度网盘手机App,操作更方便哦