笔记--Mongodb

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

1.1 为什么要使用使用数据库

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

1.2 什么是数据库

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

在这里插入图片描述

1.3 MongoDB数据库下载安装

在这里插入图片描述

1.4 MongoDB可视化软件

在这里插入图片描述

1.5 数据库相关概念

在数据库软件中可以包含多个数据仓库,在每个数据库中可以包含多个数据集合,每个
数据聚合中可以包含多条文档(集体的数据)。
术语解释说明
database数据库,mongoDB数据库软件中可以建立多个数据库
collection集合,一组数据的集合,可以解释为javascript中的数组
document文档,一条具体的数据,可以理解为javascript中的对象
field字段,文档中的属性名称,可以理解为javascript中的对象属性

下载mongoDB模块:
npm install mongoose

1.6 Mongoose第三方包

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

1.7 启动MongoDB

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

2. MongoDB数据库链接

2.1 数据库连接

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

// 引入mongoose第三方模块,用来操作数据库
const mongoose = require('mongoose');
// 数据库连接
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true })
    // 连接成功
    .then(() => console.log('数据库连接成功'))
    // 连接失败
    .catch(err => console.log(err, '数据库连接失败'))

2.2 创建数据库

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

3. MongoDB增删查改操作

3.1 创建集合

创建集合分为两步:一是对集合设定规则,二是创建集合,创建mongoose.Schema构造函数的实例即可创建集合。
// 设定集合规则
const courseSchema = new mongoose.Schema({
    name: String,
    author: String,
    isPublished: Boolean
});
// 创建集合并应用规则
const Course = mongoose.model('Course', courseSchema); // course

3.2 创建文档

创建文档实际上就是向集合中插入数据。
分为两步:
(1) 创建集合实例。
(2) 调用实例对象下的save方法将数据保存到数据库中。
// 创建集合实例
const course = new Course({
    name: 'Node.js course'.
    author: '黑马讲师',
    tags: ['node', 'backend'],
    isPublished: true
});
// 将数据保存到数据库中
course.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({
    naem: 'Node.js course', 
    author: 'Breere',
    isPublished: true  // 是否条件
});
// 将数据保存到数据库中
course.save();

3.2 创建文档(向集合中插入文档的另一种方式)

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))
// 引入mongoose第三方模块,用来操作数据库
const { truncate } = require('fs');
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
// 向集合中插入文档
// Course.create({name: '张三', author: 'breere', isPublished: true}, (err, result) => {
//     console.log(err)
//     console.log(result)
// });
Course.create({name: '张三', author: 'breere', isPublished: true})
    .then(result => console.log(result))
    .catch(err => console.log(err));

3.3 mongoDB数据库导入数据

mongoimport -d 数据库名称 -c 集合名称 -file 要导入的数据文件
找到MongoDB数据库的安装目录,将安装目录下的bin目录放置在环境变量中。

json数组导入方式:
json文件:

[{
    "name":"zhangsan",
    "age":"18",
    "email":"87654321@qq.com",
    "password":"123456",
    "hobbies":["sing","dance"]
},
{
    "name":"lisi",
    "age":"25",
    "email":"78654321@qq.com",
    "password":"213456",
    "hobbies":["sing","dance","basketball"]
},
{
    "name":"wangwu",
    "age":"33",
    "email":"68754321@qq.com",
    "password":"312456",
    "hobbies":["sing","basketball"]
},
{
    "name":"lucy",
    "age":"46",
    "email":"58764321@qq.com",
    "password":"312456",
    "hobbies":["sing","basketball","睡觉"]
},
{
    "name":"mary",
    "age":"56",
    "email":"48764321@qq.com",
    "password":"312456",
    "hobbies":["sing","basketball","吃饭"]
},
{
    "name":"jenny",
    "age":"46",
    "email":"38764321@qq.com",
    "password":"312456",
    "hobbies":["sing","basketball","睡觉","吃饭"]
}
]

终端命令:
在这里插入图片描述

3.4 查询文档

// 根据条件查找文档(条件为空则查找所有文档)
Course.find().then(result => console.log(result))

// 返回文档集合
[{
    _id: 5c0917ed39ec9b03c07cg95f,
    name: ' javascript基础',
    author: '黑马讲师'
}, {
    _id: 5c0917ed39ec9b03c56cg95f,
    name: ' javascript',
    author: '黑马讲师'	
}]
// 根据条件查找第一个文档
Course.findOne({name: 'javascript基础'}).then(result => console.log(result))

// 返回文档
{
    _id: 5c0917ed39ec9b03c07cg95f,
    name: ' javascript基础',
    author: '黑马讲师'
}
// 匹配大于,小于
User.find({age: {$gt: 10, $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));
// 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: '6141bc473f479f3d3a7b4a94'}).then(result => console.log(result));
// findOne方法返回一条文档,默认返回当前集合中的第一条文档,返回的是一条对象
User.findOne({_id: '6141bc473f479f3d3a7b4a94'}).then(result => console.log(result));
// 查询用户集合中年龄字段大于10并且小于50的文档
User.find({age: {$gt: 10, $lt: 50}}).then(result => console.log(result));
// 匹配包含
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));
// 查找年龄并且升序排列
User.find().select('age -_id').sort('age').then(result => console.log(result))
// skip跳过多少条数据,limit限制查询数据
User.find().select('age -_id').sort('age').skip(2).limit(5).then(result => console.log(result))

3.5 删除文档

// 删除单个
Course.findOneAndDelete({}).then(result => console.log(result))

// 删除多个
User.deleteMany({}).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.findOneAndDelete({}).then(result => console.log(result))
// 查找到一条文档并且删除
// 返回删除的文档
// 如果查询条件匹配了多个文档,那么将会删除第一个匹配的文档
User.findOneAndDelete({_id: '6141bc473f479f3d3a7b4a96'}).then(result => console.log(result))
// 删除多个文档
User.deleteMany({age: 18}).then(result => console.log(result))

3.6 更新文档

// 更新单个
User.updateOne({查询条件}, {要修改的值}).then(result => console.log(result))

// 更新多个
User.updateMany({查询条件}, {要修改的值}).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.updateOne({_id: '6141bc473f479f3d3a7b4a95'}, {name: '天王盖地虎'}).then(result => console.log(result))
// 更新集合中的多个文档
User.updateMany({}, {age: 18}).then(result => console.log(result))

3.6 mongoose验证

在创建集合规则时,可以设置当前字段的验证规则,验证失败就则输入插入失败。
- required:true 必传字段
- minlength:3 字符串最小长度
- maxlength:20 字符串最大长度
- min:2 数值最小为2
- max:100 数值最大为100
- enum:['html', 'css', 'javascript', 'node.js']
- trim:true 去除字符串两边的空格
- validate:自定义验证器
- default::默认值
// 引入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, '输入长度小于二'],
        // 最大长度
        maxlength: [12, '输入长度大于五'],
        // 去除插入字符串两端的空格
        trim: true
    },
    age: {
        type: Number,
        // 必填
        required: false,
        // 数字最小值
        min: [2, '年龄不能小于2'],
        // 数字最大值
        max: [100, '年龄不能超过100']
    },
    publishDate: {
        type: Date,
        // 不填的话,默认时间
        default: Date.now
    },
    category: {
        type: String,
        // 枚举,列举出当前字段可以拥有的值
        enum: ['html', 'css', 'javascript']
    },
    author: {
        type: String,
        // 自定义验证器
        validate: {
            validator: v => {
                // 返回布尔值
                // true 验证成功
                // false 验证失败
                // v 要验证的值
                return v && v.length > 4
            },
            // 自定义错误信息
            message: '传入的值不符合验证规则'
        }
    }
});
// 使用集合规则创建集合
const Post = mongoose.model('Post', postSchema);
// 向集合中插入文档
Post.create({title: '  a a   ', category: 'css', author: 'bd'}).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 postSchema = new mongoose.Schema({
    title: {
        type: String,
        // 必传字段
        required: [true, '请传入文章标题'],
        // 最小长度
        minlength: [2, '输入长度小于二'],
        // 最大长度
        maxlength: [12, '输入长度大于五'],
        // 去除插入字符串两端的空格
        trim: true
    },
    age: {
        type: Number,
        // 必填
        required: false,
        // 数字最小值
        min: [2, '年龄不能小于2'],
        // 数字最大值
        max: [100, '年龄不能超过100']
    },
    publishDate: {
        type: Date,
        // 不填的话,默认时间
        default: Date.now
    },
    category: {
        type: String,
        // 枚举,列举出当前字段可以拥有的值
        enum: {
            values: ['html', 'css', 'javascript'],
            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: '  a a   ', category: 'cssss', author: 'bd'})
    .then(result => console.log(result))
    .catch(error => {
        // 获取错误信息对象
        const err = error.errors;
        // 循环错误信息
        for (var attr in err) {
            // 将错误信息打印到控制台中
            console.log(err[attr]['message']);
        }
    });

3.7 集合关联

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

在这里插入图片描述

3.7 集合关联实现

// 用户集合
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));
// 引入mongodb第三方模块,用来操作数据库
const mongoose = require('mongoose');
// 数据库连接
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true }) // 解决当前URL解析器被废弃警告
    // 连接成功
    .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: '6141bc473f479f3d3a7b4a95'}).then(result => console.log(result));
Post.find().populate('author').then(result => console.log(result));

3.8 案例:用户信息增删改查

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

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值