day03 – 数据库
1. 数据库
存储数据的仓库。现在比较流行mysql,Oracle,mongoDB
mongoDB数据库当中有很多的数据仓库(database)
数据仓库中会有很多的集合(collection)
集合中包含很多相似的数据,这种数据叫做文档数据(document),
文档数据中有一列一列的具体属性,这种属性叫做字段(field)
2. 连接数据库
//安装第三方模块 mongoose : npm i mongoose
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground',{ useNewUrlParser: true,useUnifiedTopology: true })
.then(()=>{
console.log("数据库连接成功")
})
.catch(()=>{
console.log("数据库连接失败")
})
3. 创建集合规则,创建集合
//创建集合规则:所谓的集合规则就是用来定义数据中应该包含哪些信息
//mongoose.Schema构造函数可以用来创建集合规则对象
const studentSchema = new mongoose.Schema({
stuName:String,
stuSex:String,
stuAge:Number,
stuPhone:String
})
//根据集合规则创建集合对象
//model方法的第一个参数指的是 集合名称
//model方法的第二个参数指的是 集合使用的规则(即使用mongoose.Schema构造函数创建的集合规则)
const Student = new mongoose.model('Student',studentSchema);
4. 向集合中添加数据
save方法
//通过new Student()这种形式来创建集合中的数据
const jack = new Student({
stuName:'jack',
stuSex:'男',
stuAge:20,
stuPhone:"13888888888"
})
//如果想要让创建的数据真正的保存到数据库中,需要调用数据对象的save方法进行保存。
jack.save();
create方法
async function addStudent(info){
await Student.create(info)
}
// addStudent({stuName:"rose",stuAge:18,stuSex:"女",stuPhone:"110"});
addStudent({stuName:"lily",stuAge:17,stuSex:"女",stuPhone:"110"})
5.查询文档数据
Course.find({
name: 'wangjian',
isPublished: true
})
.limit(10),
.sort({name: 1}) // 1 升序 ‐1 降序
.select({name: 1, tags: 1})
.exec((err, data) => {})
查询符合条件的所有数据:find
find方法获取的数据是数组形式的数据
Student.find({stuSex:“女”}).then( stus => {
console.log(stus);
} )
查询符合条件的一条数据:findOne
findOne获取的数据是对象形式的数据
Student.findOne({stuSex:“女”}).then( stus => {
console.log(stus);
} )
查询符合范围条件的数据
// 匹配大于 小于
User.find({age: {gt: 20, lt: 50}}).then(result => console.log(result))
查询的是包含某个数据的文档
// 匹配包含
User.find({hobbies: {$in: [‘敲代码’]}}).then(result => console.log(result))
查询需要的几个字段
// 选择要查询的字段
User.find().select(‘name email’).then(result => console.log(result))
查询数据并排序
// 将数据按照年龄进行排序
User.find().sort(‘age’).then(result => console.log(result))
跳过某几条数据,查询limit指定的数据
// skip 跳过多少条数据 limit 限制查询数量
User.find().skip(2).limit(2).then(result => console.log(result))
6. 删除文档数据
删除一个符合条件的数据
Cat.findOneAndDelete({ 条件(比如 id 为123) }).then( result=>{
} )
删除多个
条件为空全部删除,适合删除多个有共同属性的数据
Cat.deleteMany({ }).then( result=>{
} )
7. 更新文档数据
更新一个数据
updateOne的第一个参数是设置条件(符合条件的数据才会被更新)
User.updateOne({查询条件}, {要修改的值}).then(result => console.log(result))
例:Cat.updateOne({age:2},{ name:“3岁的猫”,age:“3” })
更新多个数据
Cat.updateMany( {age:2},{ name:“3岁的猫”,age:“3” } )
8. mongoose提供的验证规则
在创建集合规则对象的时候,可以对字段进行验证规则的设置
常见验证规则:
required: true 必传字段
minlength:3 字符串最小长度
maxlength: 20 字符串最大长度
min: 2数值最小为2
max: 100 数值最大为100
enum: [‘html’, ‘css’, ‘javascript’,‘node.js’] ,只能是里面的字样类型
trim: true 去除字符串两边的空格
validate: 自定义验证器
default: 默认值
const catSchema = new mongoose.Schema({
name:String,
type:{
type:String,//设置类型必须是字符串
required:[true,'类型不能为空'],//设置必须输入内容,不能为空
minlength:2,//设置最小长度
maxlength:10//设置最大长度
trim:true //去除数据两端的空格
},
age:{
type:Number,
min:1,
max:20
},
birthday:{
type:Date,
default: Date.now //设置默认值,就算没有填入数据也会使用默认值作为birthday的结果
},
sex:{
type:String,
enum:{
values:["公","母"], //设置sex只能输入公或者母,输入其他数据的时候会报错
message:"sex只能是公或者母"
}
},
email:{
type:String,
validate:{
validator:function(val){
var reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
if(reg.test( val )){
return true;
}else{
return false;
}
},
message:"您输入的邮箱格式不正确"
}
}
})
9. 集合关联
我们进行集合数据的查询的时候,查询的数据有可能来自于多个集合。比如说有两个集合,如下:
集合Student,包含字段: name , age, classid
集合Class,包含字段:classname
需要查询所有的学生和学生所在的班级。
详情请见demo文件夹中的代码
补充:
动态页面和静态页面
静态页面指的是html代码编写的数据没有任何变化的页面
动态页面指的是页面中的内容是根据真实数据来生成的页面。
补充:
前端跳转的js代码:
location.href = "跳转页面的路径"
服务器端(后台代码)如何进行跳转:
res.writeHead(301,{
Location:'跳转页面的路径'
});
res.end();