术语:
database:数据库
collection:集合,一组数据的集合,可以理解为JS的数组,或者mysql的表
document:文档,一条具体的数据,可以理解为JS的对象,或是mysql中一行具体的数据项
field:字段,文档中的属性名称,可以理解为JS中的对象属性。
启动mongoDB的命令:net start mongoDB
关闭mongoDB的命令:net stop mongoDB
![](https://img.haomeiwen.com/i11251796/9bea76427d2ee040.png)
如果遇到“发生系统错误,拒绝访问”,记得以管理员身份打开CMD
mongoose
是一个在node.js中用于操作mongoDB 的模块
连接数据库的方法:
![](https://img.haomeiwen.com/i11251796/a57b20e37a195f50.png)
//其实在localhost后面还应加上 :端口号,
//但是mongoDB的默认值就是27017所以这里省略了
mongoose.connect('mongodb://localhost/playground')
.then(()=>{ console.log('数据库连接成功') })
.catch(err=>{ console.log('数据库连接失败',err) })
//playground是数据库的名字
创建数据库:
在mongoDB 中不需要显示的创建数据库,可以直接去使用数据库,如果mongodb发现要使用的数据库不存在,会自动帮助用户创建数据库
-
创建集合:
1 对集合设定规则
2 创建集合
使用mongoose.Schema构造函数构造规则
使用mongoose.model创建集合
eg:
image.png
//设定集合规则
const courseSchema = new mongoose.Schema({
name:String,
suthor:String,
isPublished:Boolean
});
如果在设定集合规则时,希望进行限制,可以这样:
const userSchema = new mongoose.Schema({
userName:{
type:String, //类型为字符串
required:true,//必选字段
minLength:2,//最小长度
maxLength:10//最大长度
},
email:{
type: String,
unique:ture //不可以重复!
}
})
//创建集合并应用规则(创建了Course集合)
const Course = mongoose.model('Course',sourseSchema);
//这里返回的Course是一个集合,有一些的操作。
- 创建文档
其实就是插入数据。
1 要创建集合的实例
2 调用实例对象下的save方法将数据保存到数据库中
let Course1 = new Course({
name:'node.js',
author:'it',
isPublished:true
})
Course1.save();
运行此代码后的效果
![](https://img.haomeiwen.com/i11251796/deb48e20e084a1d6.png)
数据库自动生成了_id字段,作为此数据项的唯一标识
另一种插入文档的方式:
Course.create({name:'xxx',author:'xxx',isPublished:false},(err,doc)=>{
console.log(err);
console.log(doc);
})
//和数据库相关的差不多都是异步的
Course.create({name:'xxx',author:'xxx',isPublished:false}).then(doc=>{
console.log(doc);
}).catch(err=>{console.log(err);
})
//也是可以的,所以当然也是可以使用异步函数的写法的,先留个坑,以后填
- 向mongoDB中导入数据
mongoimport -d 数据库名称 -c 集合名称 --file 要导入的文件
(要想使用,需要把mongoimport的可执行文件添加到path中)
一般,要导入的文件是json文件 - 查询文档
Course.find()
Course.find().then(result=>{ console.log(result) })
默认情况下,查询的是所有文档,返回的是一个promise对象,所以可以链式调用。
查询结果是一个数组,数组中包含多个对象,即便只有一个数据,也返回数组,即使为空,也是数组。。。
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/test',{useNewUrlParser:true})
.then(()=>{
console.log('连接成功');
}).catch(err=>{
console.log(err);
})
const courseSchema = new mongoose.Schema({
name:String,
author:String,
isPublished:Boolean
})
const Course = mongoose.model('Course',courseSchema)
Course.find().then(doc=>{
console.log(doc); //查询所有
})
Course.find({
_id:'5e0db30e2fd7c240449ed8d3'
}).then(doc=>{
console.log(doc);
})
还可以用findOne来查,只返回一个对象,默认为第一个
-
条件查询
image.png
User.find({age:{>:20,$lt:50}}).then((result)=>{console.log(result)})
//意思是,查询age大于20且小于50的文档
![](https://img.haomeiwen.com/i11251796/9ac7f3cae542c471.png)
User.find({hobbies:{$in:{'敲代码'}}}).then(doc=>{console.log(doc)})
![](https://img.haomeiwen.com/i11251796/c48494c6a9c7fd59.png)
User.find().select('name email').then(result => console.log(result))
//想要查询的只是name 和 email字段,一般来说,_id回默查询,
//如果不想让他查询,可以select('name email -_id')
![](https://img.haomeiwen.com/i11251796/848ddf7c21a3c819.png)
User.find().sort('age').then(result=>console.log(result))
//按照年龄进行升序排序
User.find().sort('-age').then(result=>console.log(result))
//降序排序
![](https://img.haomeiwen.com/i11251796/7392a15f0785380a.png)
skip(3)跳过前三条
limit(4)只查询前4条
常常在分页的时候进行使用
- 删除文档
方法:
-- findOneAndDelete({}) 作用:查找一条文档,并且删除它。如何查询条件有多条文档满足,则删除第一条
-- deleteMany({}):删除多个文档。把找到的都删了 - 更新文档
User.updateOne({查询条件},{要修改的值}).then()
User.updataMany({},{}).then() - mongoose验证
在创建集合规则时可以设置当前 字段的验证规则,验证失败则加入失败
eg:
-- required:true(字段必选)
const postSchema = new mongoose.Schema({
title:{
type:String,
required:[true,'请传入文章标题'],
minlength:2,
maxlength:[50,'文章长度不可以超过50'],
trim:true//字符串去除两边的空格
},
age:{
type:Number,
min:0,
max:120
},
date:{
type:Date,
default:Date.now
},
category:{
type:String,
enum:['node.js','java','python']//枚举,只能传入这几个,
//若是其它的,则验证失败
},
author:{
type:String,
validate:{
validater: (x)=>{ //x就是我们传入的值,对x进行验证
if() return ture //若验证成功,则返回ture,这个我们的自定义验证方法
else return false
},
message:'xxxxx' //自定义错误信息
}
}
})
//文章title是必选项,且长度为2-50个字符
常用验证如下:
![](https://img.haomeiwen.com/i11251796/0fb75a7fc1a7ef4e.png)
实现集合的关联:
const User = mongoose.model('User',new mongoose.Schema({
name:{type:String}
}))
const Post = mongoose.model("Post",new mongoose.Schema({
title:String,
author:{
type:mongoose.Schema.Types.ObjectId,ref:'User'
//字段类型是_id,与User表进行关联
}
}))
post.find().populate('author').then(result=>{
console.log(result);
})
//创建用户
User.create({name:'hah'}).then(doc=>{console.log(doc)})
//创建文章
Post.create({title:'123',author:_id}).then()
//查询
Post.find().populate('author').then(doc=>{
console.log(doc) //这样,查出来的author就不是_id,而是User表中的对应的对象
})
在存储用户密码时,通常是不可以直接进行存储的.我们需要进行加密,下面是一种常见的加密方法: bcrypt
const bcrypt = require('bcrypt')
let salt = await bcrypt.genSalt(10) //生成10个随机字符串
let pass = await bcrypt.hash('明文密码',salt)
比对密码:
let isEqual = await bcrypt .compare('明文密码','加密密码');
//返回值是一个bool类型的
bcrypt模块的依赖项比较多:
1 python 2.x
2 node-gyp
3 window-build-tools(windows环境下需要的)
如何为新数据库创建新用户
eg:
use admin
db.auth('root','root')//这里是管理员账户的 name和password
use newDataBaseName//这里我是todo
db.createUser({user:'todoMan',pwd:'todoMan',roles:['readWrite']})
连接数据库时:
mongoose.connect('mongodb://todoMan:todoMan@localhost:27017/todo',{ useNewUrlParser: true,useUnifiedTopology: true }')
Tips:
坑爹的mac catalina,不能获取根目录下的/data/db了,只能换种方法:
sudo mongod --dbpath=/Users/(你的用户名)/data/db
网友评论