MongoDB数据库
MongoDB数据库安装
Node.js通常使用MongoDB作为其数据库,具有高性能,易使用,存储数据方便等特点,完全使用JavaScript语法即可操作。下载地址:https://www.mongodb.com/download-center/community
MongoDB可视化软件:MongoDB Compass
MongoDB可视化操作软件,使用图形界面操作数据库的一种方式。下载地址:https://www.mongodb.com/download-center/compass
数据库相关概念(★★★)
在一个数据库软件中可以包含多个数据仓库,在每个数据仓库中可以包含多个数据集合,每个数据集合中可以包含多条文档(具体的数据)。
术语 | 解释说明 |
---|---|
database | 数据库,mongoDB数据库软件中可以建立多个数据库 |
collection | 集合,一组数据的集合,可以理解为JavaScript中的数组 |
document | 文档,一条具体的数据,可以理解为JavaScript中的对象 |
field | 字段,文档中的属性名称,可以理解为JavaScript中的对象属性 |
Mongoose第三方包
使用Node.js操作MongoDB数据库需要依赖Node.js第三方包mongoose,使用npm install mongoose
命令下载
MongoDB 服务开启命令行语句:net start mongodb
关闭:net stop mongodb
数据库连接
// 引用mongoose包
const mongoose = require('mongoose');
// 数据库链接
mongoose.connect('mongodb://localhost/playground') //mongodb协议/地址/数据库名称
.then(() => console.log('数据库连接成功'))
.catch(err => console.log('数据库连接失败', err));
创建集合(创建表)(★★★)
// 设置集合规则
const courseSchema = new mongoose.Schema({
name: String,
author: String,
tags: [ String ],
data: { type: Date, default: Date.now },
isPublished: Boolean
});
// 创建集合并应用规则 返回集合类(集合构造函数)
//第一个参数'Course',集合名称首字母大写,但是在数据库中实际是courses,第二个参数应用的集合规则返回当前集合的构造函数
const Course = mongoose.model('Course', courseSchema);
//创建文档
const course = new Course({
name: 'node.js基础',
author: '讲师',
isPublished: true
});
//将文档插入数据库
course.save();
//第二种方法
//写法一
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))
MongoDB数据库导入数据
mongoimport -d 数据库名称 -c 集合名称 --file 要导入的数据文件(必须先将mongoDB数据库安装目录下的bin目录配置在环境变量path中才可以)
查询文档
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,
hobbies: Array,
email: String,
password: String
});
//创建集合
const User = mongoose.model('User', userSchema);
//查询集合中数据的总数
User.countDocument({}).then(result => {
console.log(result);
});
//查询集合中所有文档,返回一个数组,如果条件为空则查找所有文档
User.find().then(result => {
console.log(result);
});
//查询集合中符合条件的文档,无论结果有几条数据都是返回一个数组,
User.find({ _id: '5c09f294aeb04b22f8460969' }).then(result => {
console.log(result);
})
//查询集合数据默认返回集合中的第一条数据,返回结果是一个对象
User.findOne().then(result => {
console.log(result);
});
User.findOne({ name: '李四' }).then(result => {
console.log(result);
})
//匹配集合中年龄大于20并且小于40的文档
User.find({ age: { $gt: 20, $lt: 40 } }).then(result => {
console.log(result);
});
//选择查询出来的字段,字段名前加-表示不要显示该字段
User.find().select('name hobbies -_id').then(result => {
console.log(result);
})
//包含
User.find({ hobbies: { $in: ['橄榄球', '足球'] } }).select('name hobbies -_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(1).limit(1).then(result => {
console.log(result);
})
删除文档
//查找到一条文档并且删除,返回的是删除的文档,查询条件匹配了多个文档那么将会删除第一个匹配的文档
User.findOneAndDelete({ _id: '5c09f294aeb04b22f8460969' }).then(result => {
console.log(result);
});
//删除多条匹配文档,如果查询条件为空,删除所有文档,返回一个对象{ n: 3, ok: 1, deletedCount: 3 }
Course.deleteMany().then(result => {
console.log(result);
});
更新文档
//更新文档 返回一个对象{ n: 1, nModified: 1, ok: 1 }
User.updateOne({ _id: '5c09f236aeb04b22f8460967' }, { name: '李铁柱' }).then(result => {
console.log(result);
});
//更新文档多个
User.updateMany({}, { hobbies: ['敲代码'] }).then(result => {
console.log(result);
});
mongoose常见的字段验证
required:true [true,自定义的错误信息] 必传字段
unique:true 设置的字段该字段不能重复
minlength:2 字符串最小长度 [2,‘自定义的错误信息’]
maxlength:5 字符串最大长度 [5,‘自定义的错误信息’]
min:2 数值最小为2
max: 100 数值最大为100
enum:['值1','值2','值3','值4'] || {values:['值1','值2','值3','值4'],message:'自定义错误信息'} 当前字段只可以填入数组中的值,否则验证不通过
trim:true 去掉字符串两边的空格
validate:{validator:(value) => {}},message:'自定义错误信息' 自定义验证器,value接收的是用户传入的值,函数返回一个布尔值,true 验证通过,false 验证失败
default 默认值
代码示例
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: '传入的值不符合验证规则'
}
}
});
如何捕获验证的错误信息
.catch(error => {
// 获取错误信息对象
const err = error.errors;
// 循环错误信息对象
for (var attr in err) {
// 将错误信息打印到控制台中
console.log(err[attr]['message']);
}
})
集合关联实现
通常不同集合的数据之间是有关系的,例如文章信息和用户信息存储在不同集合中,但文章是某个用户发表的,要查询文章的所有信息包括发表用户,就需要用到集合关联。
-
使用id对集合进行关联
-
使用populate方法进行关联集合查询
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 }
});
const postShema = mongoose.Schema({
title: {
type: String,
required: true,
minlength: 4,
maxlength: 10
},
author: {
//设定类型为系统自动生成的_id类型
type: mongoose.Schema.Types.ObjectId,
//关联集合
ref: 'User',
},
});
const User = mongoose.model('User', userSchema);
const Post = mongoose.model('Post', postShema);
//插入数据的时候需要关联起来
User .create({ name: '王五' }).then(result => console.log(result));
Post .create({ title: '射雕英雄传', author: '5c95ac7d18f84d8fac8ee4e1' }).then(resule => console.log(result));
//联合查询
Post.find({ title: 'Node.js' })
.populate('author')
.then(result => { console.log(result) })
mongoDB数据库添加账号
-
以系统管理员的方式运行powershell
-
连接数据库 mongo
-
查看数据库 show dbs
-
切换到admin数据库 use admin
-
使用db.auth(‘root’, ‘root’)命令登录数据库
-
创建超级管理员账户 db.createUser({user:'root',pwd:'root',roles:['root']})
-
切换到blog数据 use blog
-
创建普通账号 db.createUser()
-
使用exit命令退出mongodo数据库
-
卸载mongodb服务
停止服务 net stop mongodb
mongod --remove
-
创建mongodb服务
mongod --logpath="C:\ProgramFiles\MongoDB\Server\4.1\log\mongod.log" --dbpath="C:\ProgramFiles\MongoDB\Server\4.1\data" --install –-auth
-
启动mongodb服务 net start mongodb
-
在项目中使用账号连接数据库
mongoose.connect('mongodb://user:pass@localhost:port/database')