前后端交互-MongoDB数据库

一. 数据库概述及环境搭建

1 - 为什么要使用数据库

  1. 动态网站中的数据都是存储在数据库中的
  2. 数据库可以用来持久存储客户端通过表单收集的用户信息
  3. 数据库软件本身可以对数据进行高效的管理

2 - 什么是数据库

  • 数据库即存储数据的仓库,可以将数据进行有序的分门别类的存储。它是独立于语言之外的软件,可以通过API去操作它。
  • 常见的数据库软件有:mysql、mongoDB、oracle。

3 - MongoDB数据库下载安装

下载地址:https://www.mongodb.com/download-center/community

注意:上面是Windows的下载方式,mac端下载安装步骤可参考:https://blog.csdn.net/myli_binbin/article/details/110490328

4 - MongoDB Compass

MongoDB Compass 是MongoDB可视化操作软件,是使用图形界面操作数据库的一种方式。

5 - 数据库相关概念

在一个数据库软件中可以包含多个数据仓库,在每个数据仓库中可以包含多个数据集合,每个数据集合中可以包含多条文档(具体的数据)。

对应compass中如下图:

6 - Mongoose第三方包

  • 使用 Node.js 操作 MongoDB 数据库需要依赖 Node.js 第三方包 mongoose。
  • 使用npm install mongoose命令下载。

7 - 启动MongoDB

在命令行工具中运行 'net start mongoDB' 即可启动MongoDB,否则MongoDB将无法连接。

注意:MongoDB安装成功之后默认是自动启动的,如果电脑重启之后,需要手动启动MongoDB。

启动方式为:右键以管理员身份运行Windows PowerShell,输入命令:'net start mongoDB'
关闭方式为:输入命令:'net stop mongoDB'

8 - 数据库连接

使用mongoose提供的connect方法即可连接数据库。

// 引入mongoose第三方模块 用来操作数据库
const mongoose = require('mongoose');
// 数据库连接 playground是数据库名称,如果没有会自动创建
// mongoose.connect返回的是promise对象,所以可以使用.then和.catch方法
// useNewUrlParser使用新的解析器
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true})
    // 连接成功
    .then(() => console.log('数据库连接成功'))
    // 连接失败
    .catch(err => console.log(err, '数据库连接失败'));

9 - 创建数据库

在MongoDB中不需要显式创建数据库,如果正在使用的数据库不存在,MongoDB会自动创建。

二. MongoDB增删改查操作

1 - 创建集合

创建集合分为两步,一是对对集合设定规则,二是创建集合,创建mongoose.Schema构造函数的实例即可创建集合。

// 1. 设定集合规则
const courseSchema = new mongoose.Schema({
   name: String,
   author: String,
   isPublished: Boolean
});
// 2. 创建集合并应用规则 'Course'是集合名称,首字母要大写,实际上,在数据库中这个集合名称叫courses
const Course = mongoose.model('Course', courseSchema); // courses

2 - 插入文档

1. 方式一:使用save()

插入文档实际上就是向集合中插入数据。分为两步:

  1. 创建集合实例
  2. 调用实例对象下的save方法将数据保存到数据库中
// 引入mongoose第三方模块 用来操作数据库
const mongoose = require('mongoose');
// 数据库连接
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true})
    // 连接成功
    .then(() => console.log('数据库连接成功'))
    // 连接失败
    .catch(err => console.log(err, '数据库连接失败'));

// 创建集合规则
const courseSchema = new mongoose.Schema({
    name: String,
    author: String,
    isPublished: Boolean
});

// 使用规则创建集合 返回的是集合的构造函数,因为构造函数中有好多方法可以让我们来操作集合中的数据
// 1.集合名称
// 2.集合规则
const Course = mongoose.model('Course', courseSchema) // courses

// 创建文档
const course = new Course({
    name: 'node.js基础',
    author: '黑马讲师',
    isPublished: true
});
// 将文档插入到数据库中
course.save();

插入文档之后在compass里面查看数据,结果如下:

2. 方式二:使用create()

使用create方法,第一个参数是对象类型,第二个参数是回调函数,当文档插入完成之后会调用这个回调函数。

Course.create({name: 'JavaScript基础', author: '黑马讲师', isPublish: true}, (err, doc) => { 
     //  错误对象
    console.log(err)
     //  当前插入的文档
    console.log(doc)
});

create方法返回的是promise对象,所以可以用.then

Course.create({name: 'JavaScript基础', author: '黑马讲师', isPublish: true})
      .then(doc => console.log(doc))
      .catch(err => console.log(err))

3 - mongoDB数据库导入数据

使用mongoimport命令之前,需要将mongoimport.exe可执行文件的bin目录放入系统环境变量之中,否则无法在终端使用mongoimport命令。

步骤如下:

  1. 找到MongoDB数据库安装目录下的mongoimport.exe文件的文件目录,例如:C盘/Program Files/MongoDB/Server/4.1/bin。
  2. 点击我的电脑->右键属性->高级系统设置->环境变量->找到系统变量下的Path,双击打开->点击新建->将刚才的目录拷贝进去-> 点击确认。
  3. cd到要导入的数据文件的目录,使用命令:mongoimport –d 数据库名称 –c 集合名称 –-file 要导入的数据文件,将文件中的数据导入数据库。例如:mongoimport -d playground -c users --file ./user.json,如果提示 “imported 6 documents” 说明导入成功。

注意:如果是mac电脑,可以使用compass导入json文件,然后填入数据库名字和文档名字即可,如下图:

user.json文件如下:

{"_id":{"$oid":"5c09f1e5aeb04b22f8460965"},"name":"张三","age":20,"hobbies":["足球","篮球","橄榄球"],"email":"[email protected]","password":"123456"}
{"_id":{"$oid":"5c09f236aeb04b22f8460967"},"name":"李四","age":10,"hobbies":["足球","篮球"],"email":"[email protected]","password":"654321"}
{"_id":{"$oid":"5c09f267aeb04b22f8460968"},"name":"王五","age":25,"hobbies":["敲代码"],"email":"[email protected]","password":"123456"}
{"_id":{"$oid":"5c09f294aeb04b22f8460969"},"name":"赵六","age":50,"hobbies":["吃饭","睡觉","打豆豆"],"email":"[email protected]","password":"123456"}
{"_id":{"$oid":"5c09f2b6aeb04b22f846096a"},"name":"王二麻子","age":32,"hobbies":["吃饭"],"email":"[email protected]","password":"123456"}
{"_id":{"$oid":"5c09f2d9aeb04b22f846096b"},"name":"狗蛋","age":14,"hobbies":["打豆豆"],"email":"[email protected]","password":"123456"}

4 - 查询文档

导入数据之后就可以查询文档了,如下:

// 引入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);

// find()方法返回的都是一个数组,如果不传参数,默认查询用户集合中的所有文档
// User.find().then(result => console.log(result));

// 通过_id字段查找文档(find方法,参数传入一个对象)
// 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))

// 选择要查询的字段,_id字段是默认查询的,想查询name email字段,不想查询_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))

// 查询文档跳过前两条结果,限制显示3条结果,skip和limit配合可以做分页功能
User.find().skip(2).limit(3).then(result => console.log(result))

5 - 删除文档

// 删除单个文档,参数是一个对象,返回的是删除的那个文档,如果匹配了多个文档,只删除匹配到的第一个文档
User.findOneAndDelete({}).then(result => console.log(result))
// 删除多个文档,如果参数传递为空,则删除全部文档,返回的是一个对象{n:4,ok:1},n代表删除了4个文档,ok为1代表删除成功
User.deleteMany({}).then(result => console.log(result))

6 - 更新文档

// 更新单个,返回的是一个对象,如果ok为1,代表更新成功
User.updateOne({查询条件}, {要修改的值}).then(result => console.log(result))
// User.updateOne({name: '李四'}, {age: 120, name: '李狗蛋'}).then(result => console.log(result))
// 更新多个,返回的是一个对象,如果ok为1,代表更新成功
User.updateMany({查询条件}, {要更改的值}).then(result => console.log(result))
// User.updateMany({}, {age: 300}).then(result => console.log(result))

7 - mongoose集合规则验证

在创建集合规则时,可以设置当前字段的验证规则,验证失败则数据插入失败。

  • required: true 必传字段
  • minlength:3 字符串最小长度3
  • maxlength: 20 字符串最大长度20
  • min: 2 数值最小为2
  • max: 100 数值最大为100
  • enum: ['html', 'css', 'javascript', 'node.js'] 列举出当前字段只能传数组中的那些值
  • trim: true 去除字符串两边的空格
  • validate: 自定义验证器
  • default: 默认值

以前我们创建集合规则只指定了字段的类型,如下:

const courseSchema = new mongoose.Schema({
   name: String,
   author: String,
   isPublished: Boolean
});

现在我们创建集合规则的时候可以多加一些验证条件,如果不符合验证条件,则数据操作失败,如下:

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: '传入的值不符合验证规则'
        }
    }
});

补充:上面我们知道了,如果集合规则验证失败,则数据操作失败,返回错误对象,所有的验证失败字段都会被包裹成一个对象,放入error.errors数组中,使用error.errors['字段名称'].message拿到每一个验证失败字段的错误信息,代码如下:

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']);
        }
    })

8 - 集合关联

通常不同集合的数据之间是有关系的,例如文章信息和用户信息存储在不同集合中,但文章是某个用户发表的,要查询文章的所有信息包括发表用户,就需要用到集合关联。

  • 使用id对集合进行关联
  • 使用populate方法进行关联集合查询

集合关联实现:

// 引入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
    },
    // 文章作者的id值
    // 使用ID将文章集合和作者集合进行关联
    // ObjectId是固定写法,代表_id
    // ref: 'User'代表和User集合进行关联
    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({titile: '123', author: '5c0caae2c4e4081c28439791'}).then(result => console.log(result));
Post.find().then(result => console.log(result))
// 查询结果为:[{_id:5c0cj7e4b94ndk93m0ij089,author:83jk93v6s18db7dm8,__v:0}] 这里的author是作者的id信息
Post.find().populate('author').then(result => console.log(result))
// 查询结果为:[{_id:5c0cj7e4b94ndk93m0ij089,author:{_id:83jk93v6s18db7dm8,name:'itheima',__v:0},__v:0}]  这里的author是作者的具体信息

三. 案例:用户信息增删改查

  1. 搭建网站服务器,实现客户端与服务器端的通信
  2. 连接数据库,创建用户集合,向集合中插入文档
  3. 当用户访问/list时,将所有用户信息查询出来
  4. 将用户信息和表格HTML进行拼接并将拼接结果响应回客户端
  5. 当用户访问/add时,呈现表单页面,并实现添加用户信息功能
  6. 当用户访问/modify时,呈现修改页面,并实现修改用户信息功能
  7. 当用户访问/delete时,实现用户删除功能

1 - 数据文件导入

在写代码之前,首先把数据导入数据库,由于我的是mac电脑,不会视频里讲的使用命令行的方式导入(视频里讲的是windows的导入方式),所以手动导入数据,步骤如下:

  1. 打开compass,点击左下角的 + 号,填写数据库名称为playground,文档名称为users,如下图:

注意:文档名称为users,对应到代码里面就是User。

  1. 点击ImportData,选中上面的user.json文件,选中json,点击导入即可,如下:

2 - 代码编写

首先创建database文件夹,我们就在这个文件夹里面写代码,cd到当前文件夹,执行npm init -y生成package.json文件,由于我们需要使用mongoose操作数据库,所以需要下载mongoose第三方库,执行npm install mongoose下载。最终的文件目录结构如下:

上面model文件夹中的两个文件,是为了使代码更具模块化而分离的用于连接数据库的模块(index.js)和用于创建集合的模块(user.js),案例的详细代码如下,在终端执行node app.js就可以把项目跑起来,然后在浏览器访问:http://localhost:3000/list,即可访问项目。

app.js文件:

// 搭建网站服务器,实现客户端与服务器端的通信
// 连接数据库,创建用户集合,向集合中插入文档
// 当用户访问/list时,将所有用户信息查询出来
//  实现路由功能
//  呈现用户列表页面
//  从数据库中查询用户信息 将用户信息展示在列表中
// 将用户信息和表格HTML进行拼接并将拼接结果响应回客户端
// 当用户访问/add时,呈现表单页面,并实现添加用户信息功能
// 当用户访问/modify时,呈现修改页面,并实现修改用户信息功能
//  修改用户信息分为两大步骤
//      1.增加页面路由 呈现页面
//          1.在点击修改按钮的时候 将用户ID传递到当前页面
//          2.从数据库中查询当前用户信息 将用户信息展示到页面中
//      2.实现用户修改功能
//          1.指定表单的提交地址以及请求方式
//          2.接受客户端传递过来的修改信息 找到用户 将用户信息更改为最新的
// 当用户访问/delete时,实现用户删除功能

const http = require('http');

const url = require('url');
const querystring = require('querystring');

// 连接数据库模块
require('./model/index.js');
// 创建集合模块
const User = require('./model/user.js');

// 创建服务器
const app = http.createServer();

// 为服务器对象添加请求事件
app.on('request', async (req, res) => {
    // 请求方式
    const method = req.method;
    // pathname请求地址  query请求参数
    const { pathname, query } = url.parse(req.url, true);

    if (method == 'GET') {
        if (pathname == '/list') { // 呈现用户列表页面
            // 查询用户信息  这里不使用.then,我们使用await,await关键字只能使用在异步函数中,所以app.on函数加一个async
            let users = await User.find();
            // 将html标签存在变量里面,这里是html头部
            let list = `
                
                
                
                    
                    用户列表
                    
                
                
                    
添加用户
`; // 对数据进行循环操作 // 拼接用户名 年龄 ${item.name} 是模板字符串的特定写法 users.forEach(item => { list += ` `; }); // 拼接底部 list += `
用户名 年龄 爱好 邮箱 操作
${item.name} ${item.age} `; // 拼接用户习惯 hobbies是个数组 item.hobbies.forEach(item => { list += `${item}`; }) // 拼接邮箱 删除修改按钮 // 点击修改、删除按钮,将用户的id传递过去 list += ` ${item.email} 删除 修改
`; // 将html标签响应给客户端 res.end(list); } else if (pathname == '/add') { // 呈现添加用户信息界面 // 呈现添加用户表单页面 let add = ` 用户列表

添加用户

`; res.end(add) } else if (pathname == '/modify') { // 呈现修改用户信息界面 // 从数据库中查询用户信息,使用findOne方法,结果是一个对象 let user = await User.findOne({_id: query.id}); let hobbies = ['足球', '篮球', '橄榄球', '敲代码', '抽烟', '喝酒', '烫头', '吃饭', '睡觉', '打豆豆'] console.log(user) // 呈现修改用户表单页面 // method="post" action="/modify?id=${user._id} 指定表单提交的方式和地址、参数 let modify = ` 用户列表

修改用户

`; // 处理用户爱好数据 hobbies.forEach(item => { // 判断当前循环项在不在用户的爱好数据组 let isHobby = user.hobbies.includes(item); if (isHobby) { modify += ` ` } else { modify += ` ` } }) modify += `
`; res.end(modify) } else if (pathname == '/remove') { // 删除用户信息 // res.end(query.id) await User.findOneAndDelete({_id: query.id}); res.writeHead(301, { Location: '/list' }); res.end(); } }else if (method == 'POST') { // 点击添加用户按钮的时候就会走到这里来,这里是POST请求 上面的/add呈现添加界面是GET请求 if (pathname == '/add') { // 接受用户提交的信息 let formData = ''; // 接受post参数 req.on('data', param => { formData += param; }) // post参数接受完毕 req.on('end', async () => { let user = querystring.parse(formData) // 将用户提交的信息添加到数据库中 这里使用await,所以面使用async await User.create(user); // 301代表重定向 // location 跳转地址 res.writeHead(301, { Location: '/list' }); // 请求结束 res.end(); }) }else if (pathname == '/modify') { // 点击修改用户信息会走到这里 // 接受用户提交的信息 let formData = ''; // 接受post参数 req.on('data', param => { formData += param; }) // post参数接受完毕 req.on('end', async () => { let user = querystring.parse(formData) // 将用户提交的信息添加到数据库中 await User.updateOne({_id: query.id}, user); // 301代表重定向 // location 跳转地址 res.writeHead(301, { Location: '/list' }); res.end(); }) } } }); // 监听端口之后,在浏览器中使用:http://localhost:3000/list即可访问 app.listen(3000);

连接数据库模块:

// mongoose模块是第三方模块,当前文件目录下没有这个模块,但是当前目录的node_modules文件夹下有mongoose模块,所以模块可以引用成功
// 在user.js和index.js中都引用了mongoose第三方模块,不会造成性能浪费,因为引入一次之后下一次就是从缓存中拿了
const mongoose = require('mongoose');
// console.log(mongoose));
// 数据库连接 27017是mongodb数据库的默认端口,可以不写,不写默认就是这个端口
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true ,useUnifiedTopology: true })
    .then(() => console.log('数据库连接成功'))
    .catch(() => console.log('数据库连接失败'));

创建集合模块:

// mongoose模块是第三方模块,当前文件目录下没有这个模块,但是当前目录的node_modules文件夹下有mongoose模块,所以模块可以引用成功
// 在user.js和index.js中都引用了mongoose第三方模块,不会造成性能浪费,因为引入一次之后下一次就是从缓存中拿了
const mongoose = require('mongoose');
// 创建用户集合规则
const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 20
    },
    age: {
        type: Number,
        min: 18,
        max: 80
    },
    password: String,
    email: String,
    hobbies: [ String ]
});

// 创建集合 返回集合构造函数
const User = mongoose.model('User', userSchema);

module.exports = User;

代码地址:https://github.com/iamkata/mongoDB-case

上面代码问题总结:

  1. 代码的大小写特别重要,否则代码有可能执行出错
  2. 方法调用要加()否则出错
  3. 一行结束要有分号; 切记

上面项目还有一个问题,就是html结构是通过字符串拼接的,可维护性比较差,下面讲一下模板引擎来解决这个问题。

你可能感兴趣的:(前后端交互-MongoDB数据库)