MongoDB基础
# MongoDB基础
# MongoDB第三方包
- 使用
Node.js
操作MongoDB
数据库需要依赖Node.js
第三方包mongoose
- 使用
npm install mongoose
命令下载
# 启动 MongoDB
在命令行工具中运行
net start mongoDB
即可启动MongoDB
,否则MongoDB
将无法连接net stop mongoDB
可以暂停服务
# 数据库连接
使用mongoose提供的connect方法即可连接数据库。
mongoose.connect('mongodb://localhost/playground')
.then(() => console.log('数据库连接成功'))
.catch(err => console.log('数据库连接失败', err));
2
3
特殊情况
(node:51780) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(node:51780) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
2
这种情况下,虽然可以连接数据库,但是提示说明有些模块以后将不再支持,所以要通过设置才能完美连接。
按照提示信息,需要在mongoose.connect()
方法传入第二个参数。第二个参数是一个对象。设置如下
monogoose.connect('mongodb://localhost/playground',{ useNewUrlParser: true , useUnifiedTopology: true })
.then(result => console.log('连接成功!'))
.catch(err => console.log('连接失败!'))
2
3
这样就能完美链接,没有提示信息了。
# 创建数据库
在MongoDB中不需要显式创建数据库,如果正在使用的数据库不存在,MongoDB会自动创建。
# 创建集合
创建集合分为两步
一是对对集合设定规则,使用
mongoose.Schema
得到集合的约束。参数为一个对象,其属性为集合的约束。二是创建集合, 使用
mongoose.model
创建数据集合的构造函数。第一个参数是 集合名称,第二个参数是集合的约束
// 设定集合规则
const courseSchema = new mongoose.Schema({
name: String,
author: String,
isPublished: Boolean
});
// 创建集合并应用规则
const Course = mongoose.model('Course', courseSchema); // courses
2
3
4
5
6
7
8
9
mongoose.Schema()
接收一个对象为参数,对象的属性为数据集合的字段,返回一个数据集合的约束条件mongoose.model()
返回的是一个集合的集合的构造函数
注意
在连接的数据库没有被创建时,没有插入数据,就不会创建数据库
# 创建文档
创建文档实际上就是向集合中插入数据。
# 插入数据方式一
- 创建集合实例
- 调用实例对象下的
save
方法将数据保存到数据库中。
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('成功'))
.catch(() => { console.log("失败") })
//创建集合约束
const courseSchema = new mongoose.Schema({
name: String,
author: String,
isPubilshed: Boolean
})
//得到构造函数 mongoose.model()规定第一个参数首字母大写 如 'Course'
const Course = mongoose.model('Course', courseSchema)
//实例化集合构造函数
const course = new Course({
name:'leochen',
author:'coder',
isPubilshed:'true'
})
//将数据插入到数据库中
course.save()
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
# 插入数据方式二
使用数据集合的create方法,可以创建文档(插入数据)。
create方法
- 参数一:数据对象
- 参数二:回调函数,回调函数中又传入了两个参数,第一个参数为错误对象,第二个参数为插入的文档
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('成功'))
.catch(() => { console.log("失败") })
//创建集合约束
const courseSchema = new mongoose.Schema({
name: String,
author: String,
isPubilshed: Boolean
})
//得到构造函数 mongoose.model()规定第一个参数首字母大写 如 'Course'
const Course = mongoose.model('Course', courseSchema)
Course.create({name:'cyx',author:'ugly',isPubilshed:false},(err,data)=>{
if(err){
console.log(err)
return
}
console.log(data)
})
//也可以使用promise的方式的到异步操作的执行结果
Course.create({name: 'JavaScript基础', author: '黑马讲师', isPubilshed: true})
.then(doc => console.log(doc))
.catch(err => console.log(err))
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
注意
也可以使用promise的方式的到异步操作的执行结果
# 导入数据
使用
mongoimport –d 数据库名称 –c 集合名称 --file 要导入的数据文件
找到mongodb
数据库的安装目录,将安装目录下的bin
目录放置在环境变量中。
mongoimport -d playground -c users --file ./user.json
# 查询文档
使用
Cousrse.find()
方法来查询文档
查询所有文件
//引入第三方模块,操作数据库
const mongoose = require('mongoose')
//连接数据库
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true
})
.then(() => console.log('连接成功'))
.catch(err => console.log('连接出错'))
let userScheme = new mongoose.Schema({
name: String,
age: Number,
email: String,
password: String,
hobbies: [String]
})
const User = mongoose.model('User', userScheme)
User.find().then(result => console.log(result))
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# find()方法
find()
方法可以传入查询条件参数,指定查找某个数据,查询条件参数为一个一查询条件为属性的对象。返回一个数组,如果不存在也返回一个空数组。这个方法返回的是promise对象,可以使用then() catch() 方法处理异步操作的结果
User.find({ _id: '5c09f267aeb04b22f8460968' }).then(result => console.log(result))
//结果
[
{
hobbies: [ '敲代码' ],
_id: 5c09f267aeb04b22f8460968,
name: '王五',
age: 25,
email: 'wangwu@itcast.cn',
password: '123456'
}
]
2
3
4
5
6
7
8
9
10
11
12
13
# findOne()方法
执行如下代码,默认返回第一条数据,以对象的形式返回。这个方法返回的是promise对象,可以使用then() catch() 方法处理异步操作的结果
User.findOne().then(result => console.log(result))
//结果
{
hobbies: [ '足球', '篮球', '橄榄球' ],
_id: 5c09f1e5aeb04b22f8460965,
name: '张三',
age: 20,
email: 'zhangsan@itcast.cn',
password: '123456'
}
2
3
4
5
6
7
8
9
10
11
给定条件与find()
方法相同
User.findOne({name:'李四'}).then(result => console.log(result))
//结果
{
hobbies: [ '足球', '篮球' ],
_id: 5c09f236aeb04b22f8460967,
name: '李四',
age: 10,
email: 'lisi@itcast.cn',
password: '654321'
}
2
3
4
5
6
7
8
9
10
11
# 查询条件
- 大于小于
$gt
代表大于$lt
代表小于
//查找年龄大于 20 小于 50 的数据
User.find({age: {$gt: 20, $lt: 50}}).then(result => console.log(result))
2
匹配包含
使用 $in 来作为匹配包含条件的特殊符号
//找出 hobbies 里面含有敲代码的
User.find({hobbies: {$in: ['敲代码']}}).then(result => console.log(result))
2
选择查询字段
find().select('字段1 字段2 -字段3 ...')
字段之间用空格隔开,如果不想查询某字段,就在他前面加上一个'-',字段3 就不想被查询结构展示出来
//查询结果字段之包含name和email
User.find().select('name email').then(result => console.log(result))
2
查询结果排序
使用
find().sort('-字段')
来对结果进行升序排列,如果向降序排列,那么就在字段的前面加上'-'
//根据年龄升序排列
User.find().sort('age').then(result => console.log(result))
2
skip
跳过多少条数据limit
限制查询数量
//跳过前两行,并每次只展示两条数据
User.find().skip(2).limit(2).then(result => console.log(result)
2
# 删除文档
# 删除单个
// 删除单个
Course.findOneAndDelete({条件}).then(result => console.log(result))
//删除李四
User.findOneAndDelete({name:'李四'}).then(result=> console.log(result))
2
3
4
5
如果给定条件,有多条满足数据,那么只返回第一条
# 删除多个
// 删除多个
User.deleteMany({}).then(result => console.log(result))
2
# 文档更新
更新即修改
// 更新单个文档
User.updateOne({查询条件}, {要修改的值}).then(result => console.log(result))
2
// 更新多个文档
User.updateMany({查询条件}, {要更改的值}).then(result => console.log(result))
2
这两个方法的返回值都是promise
对象