8 链接数据库

8.1 回顾ES6

ES6对数组新增了很多方法
可以用Array.prototype在浏览器中查看所有属性

  1. find
    • find接收一个方法作为参数,方法内部返回一个条件
    • find会便利所有的元素,执行你给定的带有条件返回值的函数
    • 符合该条件的元素会作为find方法返回值
    • 如果遍历结束还没有符合该条件的元素,则返回undefined
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var users = [
{id:1,name:'张三1'},
{id:2,name:'张三2'},
{id:3,name:'张三3'},
{id:4,name:'张三4'}
]

Array.prototype.myFind = function(conditionFunc) {
for (var i = 0;i< this.length;i++){
if(conditionFunc(this[i],i)){
return this[i]
}
}
}

var ret - users.myFind(function(item,index) {
return item.id === 4
})

console.log(ret)

8.2 关系和非关系型数据库

  • 所有的关系型数据库都需要通过sql语言来操作
  • 所有的关系型数据库在操作之前都需要设计表结构
  • 数据表支持约束
    • 唯一的
    • 主键
    • 默认值
    • 非空
  • 非关系型数据库非常灵活
  • 有的关系型数据库就是key-value键值对
  • MongoDB是长得最像关系型数据库的非关系型数据库
    • 数据库-》数据库
    • 数据表-》集合(数组)
    • 表记录-》(文档对象)

8.3 Mongod数据库基本操作

Mongod的安装和其他操作可以看另一篇文章

  1. 启动和关闭数据库
    启动:

mongod默认使用,执行mongod命令所处盘符目录下的/data/db作为自己的数据存储
所以在第一次执行该命令之前先自己手动建立一个data/db

mongod

如果想要修改默认的数据存储牡蛎可以

mongod –dppath=数据存储目录路径

停止:

在开启服务的控制台,直接Ctrl+c即可停止
或者直接关闭开启服务控制台也可以

  1. 连接和退出数据库

连接:
默认连接本机的MongoDB服务

mongo

退出:
在连接状态下输入exit退出连接

exit


8.4 mongoose

mongoose是Node连接mongo的包,查看官网

  1. 起步
    安装

    npm i mongoose

下面是官网的示例
hello world:

1
2
3
4
5
6
7
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

const Cat = mongoose.model('Cat', { name: String });

const kitty = new Cat({ name: 'Zildjian' });
kitty.save().then(() => console.log('meow'));

下面我们自己写一个demo

  • 连接数据库
  • 设计文档结构(表结构)
  • 将文档结构发布为模型
  • 开始操作
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    const mongoose = require('mongoose');
    // 1.连接数据库
    // 指定连接的数据库不需要存在,当你插入第一条数据之后就会自动被创建出来
    mongoose.connect('mongodb://localhost/itcast');

    // 2. 设计集合结构(表结构)
    // 字段名称就是表结构中的属性名称
    // 约束的目的就是为了保证数据的完整性,不要有脏数据

    var userSchema = new Schema({
    username:{
    type:String, // 数据类型
    required:ture //必须有
    },
    password:{
    type:String,
    required:true
    },
    email:{
    type: String
    }
    })

    // 3. 将文档结构发布为模型
    // mongoose.model方法就是用来将一个框架发布为model
    // 第一个参数:传入一个大写单词单数字符串来表示你的数据库名称
    // mongoose会自动将大写名词的单字符串生成小写复数的集合名称
    // 例如这里的User最终会变成users集合名称
    // 第二个参数:架构Schema
    // 返回值:模型构造函数
    var User = mongoose.model('User',userSchema)
    // 4. 当我们有了模型构造函数之后,就可以使用这个构造函数对users集合中的数据进行操作
    var admin = new User({
    username:'admin',
    password:'123456',
    email:'admin@163.com'
    })

    admin.save(function(err,ret) {
    if(err){
    console.log('保存失败')
    }else{
    console.log('保存成功')
    console.log(ret)
    }
    })
  1. 增加数据

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    var admin = new User({
    username:'admin',
    password:'123456',
    email:'admin@163.com'
    })

    admin.save(function(err,ret) {
    if(err){
    console.log('保存失败')
    }else{
    console.log('保存成功')
    console.log(ret)
    }
    })
  2. 查询

  • 查询所有

    1
    2
    3
    4
    5
    6
    7
    User.find(function(err,ret) {
    if(err){
    console.log('查询失败')
    }else{
    console.log(ret)
    }
    })
  • 按条件查询所有

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    User.find({
    username:'admin',
    password:'123456',
    },function(err,ret) {
    if(err){
    console.log('查询失败')
    }else{
    console.log(ret)
    }
    })
  • 按条件查询一个

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    User.findOne({
    username:'admin',
    password:'123456',
    },function(err,ret) {
    if(err){
    console.log('查询失败')
    }else{
    console.log(ret)
    }
    })
    `

4 删除
根据条件删除所有:

1
2
3
4
5
6
7
8
9
10
11
User.remove({
username:'admin',
password:'123456',
},function(err,ret) {
if(err){
console.log('删除失败')
}else{
console.log('删除成功')
console.log(ret)
}
})

根据条件删除一个:

1
Model.findOneAndRemove(conditions,[options],[callback])

根据id删除一个:

1
Model.findByIdAndRemove(id,[options],[callback])

4 更新数据
根据条件更新所有

1
Model.update(conditions,doc,[options],[callback])

根据条件更新一个

1
Model.findOneAndUpdate([conditions],[update],[options],[callback])

根据id更新一个

1
2
3
4
5
6
7
8
9
10
User.findByIdAndUpdate('23213123123123',{
password:'1234',
},function(err,ret) {
if(err){
console.log('更新失败')
}else{
console.log('更新成功')
console.log(ret)
}
})

8.5 更新项目为数据库存储

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/itcast')
var Schema = mongoose.Schema
var studentSchema = new Schema({
name:{
type:String,
required:true
},
gender:{
type:Number,
enum:[0,1],
default:0
},
age:{
type:Number,
required:true
},
hobbies:{
type:String
}
})

module.exports = mongoose.model('Student',studentSchema);

渲染学生列表页面修改

1
2
3
4
5
6
7
8
9
10
router.get('/students',function(req,res) {
Student.find(function(err,students) {
if(err){
return res.status(500).send('Server error')
}
res.render('index.html',{
students:students
})
})
})

处理添加学生

1
2
3
4
5
6
7
8
router.post('/students/new',function(req,res) {
new Student(req,body).save(function(err) {
if(err){
return res.status(500).send('Server error')
}
res.redirect('/students')
})
})

8.6 连接Mysql

应用的包名称为mysql

npm install mysql

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var mysql = require('mysql')

// 1.创建连接
var connection = mysql.createConnection({
host:'localhost', // 地址
user:'me', // 账户
password:'***', // 密码
database:'xxx' // 数据库名
})
// 2. 连接数据库
connection.connet();

// 3. 执行数据操作(增删改查所有语句都在这里执行)
connection.query('SQL语句',function(error,results,fields) {
if(error) throw error;
console.log(results[0].solution)

})
// 4. 关闭连接
connection.end();

9 回调函数

9.1 回调地狱

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var fs = require('fs')
fs.readFile('./data/a.txt','utf8',function(err,data) {
if(err){
// 抛出异常
// 1. 阻止程序的执行
// 2. 把错误消息打印到控制台
throw err
}
console.log(data);
})
fs.readFile('./data/b.txt','utf8',function(err,data) {
if(err){
throw err
}
console.log(data);
})
fs.readFile('./data/c.txt','utf8',function(err,data) {
if(err){
throw err
}
console.log(data);
})
```

如果想一个一个执行只能嵌套,影响美观
```js
var fs = require('fs')
fs.readFile('./data/a.txt','utf8',function(err,data) {
if(err){
// 抛出异常
// 1. 阻止程序的执行
// 2. 把错误消息打印到控制台
throw err
}
console.log(data);
fs.readFile('./data/b.txt','utf8',function(err,data) {
if(err){
throw err
}
console.log(data);
fs.readFile('./data/c.txt','utf8',function(err,data) {
if(err){
throw err
}
console.log(data);
})
})
})

9.2 Promise

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var fs = require('fs')
console.log(1)
// 创建Promise容器
// 1. 给别人一个承诺
// Promise容器一旦创建,就开始执行里面的代码
new Promise(function() {
console.log(2)
fs.readFile('./data/a.txt','utf8',function(err,data) {
if(err){
throw err
}
console.log(3)
console.log(data);
})
})
console.log(4)

最后更新: 2018年12月24日 11:52

原始链接: http://linjiad.github.io/2018/12/24/NodeJs3/

× 请我吃糖~
打赏二维码