mongoDB
npm install mongoose //node需要操作数据库依赖的第三方模块
net stop mongodb 关闭mongobd //每次开机前需要调用
net start mongodb 开启mongobd
数据库
使用mongoose.Schema创建集合规则
//引入第三方模块 const mongoose = require('mongoose') //连接数据库 mongoose.connect('mongodb://localhost/playground',{ useNewUrlParser: true,useUnifiedTopology: true })//兼容配置 .then(() => console.log('数据库连接成功')) .catch(() => console.log('数据库连接失败')); //实例化mongoose.Schema构造函数,创建集合规则 const courseSchema = new mongoose.Schema({ name:String, author:String, isPublished:Boolean //是否带有课程状态,这些都被称之为集合中的字段 }) //使用规则创建集合,返回一个集合构造函数(Course) //参数1:集合名称 //参数2:集合规则 const Course = mongoose.model('Course',courseSchema) //courses //通过集合构造函数船舰文档,返回一个文档实例 const course = new Course({ name:"课程名称", author:"李良荣", isPublished:false }) //保存文档 course.save()
集合
创建集合
-
安装并导入mongoose模块,并使用mongoose.connect连接数据库
-
使用new mongoose,Schema创建集合规则
-
使用mongoose.model创建集合对象(参数1:集合名称,参数2:集合规则)
-
Date.now设置默认时间
-
mongoose验证
-
required:true 必传字段
-
minlength/maxlength字符串长度限制
-
min/max数字大小限制
-
enum:可枚举的选项
-
trim去空格,default默认值
-
validata:自定义验证器
//实例化mongoose.Schema构造函数,创建集合规则 const courseSchema = new mongoose.Schema({ name:{ //mongoose字段验证 type:String, //设置改字段为必填字段 required:[true,'错误描述'], minlength:[2,'字符串最小长度为2'], maxlength:[5,'字符串最大长度为5'], trim:true }, age:{ type:Number, min:18, max:100 }, date:{ type:Date, default:Date.now //设置默认为当前时间 } author:{ type:String, default:'李良荣', //枚举当前字段可以拥有的值 enum:{ value:['李良荣','帅哥'], message:'错误信息' } } }) //使用规则创建集合,返回一个集合构造函数(Course) //参数1:集合名称 //参数2:集合规则 const Course = mongoose.model('Course',courseSchema) //courses
导入集合
-d数据库名 -c 集合名 --file 导入的文件
例: mongoimport -d playground -c users --file ./user.json
关联集合
-
在规则中需要设置type:mongoose.Schema.Types.ObjectId,需要传入ref关联对象
-
在创建对象时,在字段中传入关联对象id
-
通过find().populate('字段')查看数据
//实例化mongoose.Schema构造函数,创建集合规则 const courseSchema = new mongoose.Schema({ name:String, author:{ //在这里对User进行关联 type:mongoose.Schema.Types.ObjectId, ref:'User' }, isPublished:Boolean //是否带有课程状态,这些都被称之为集合中的字段 }) //创建对象时,传入关联ID Course.create({name:'一本书',author: '5c09f2d9aeb04b22f846096b',isPublished:false}) //查询时需要在find后加上populate才能将id变成数据展示出来 Course.find({name:'一本书'}).populate('author').then(res=>{ console.log(res); })
文档
创建文档
-
方式一:new 集合对象
-
方式二:集合对象的create方法创建
-
方式三:跟二一样,为了方便可以使用promise
//通过集合构造函数创建文档,返回一个文档实例 const course = new Course({ name:"测试", author:"李良荣", isPublished:false }) //保存文档,第一种方式需要保存 course.save() //创建文档的第二种方式 Course.create({name:'课程1',author:'李良荣',isPublished:false},(err,res)=>{ console.log(err); console.log(res); }) //创建文档的第三种方式,支持promise Course.create({name:'课程2',author:'李良荣',isPublished:false}) .then(res=>{ console.log(res); }) .catch(err=>{ console.log(err); })
查询文档
-
集合.find返回查询到的所有文档,()里放查询条件
-
集合.findOne返回到的一条文档,
-
$in包含 $gt大于 $lt小于
-
find().select('name','emial','-_id')过滤查询,添加-号删除
-
find().sort('age')排序(从小到大),添加-倒过来
-
find().skip(2)跳过多少条数据 ,一般用于分页
-
find().limit(2)限制查询数量一般用于分页
-
countDocuments({})查询数据的总数量
-
find().populate('author')多集合联合查询,查询联合表内的所有author信息
//按升序查询年龄在10-25岁之间喜欢踢足球的人的姓名 User.find({hobbies:{$in:['足球']},age:{$gt:10,$lt:25}}) .select(['age','name','-_id']).sort('age') .then(res=>{ console.log(res); }) User.findOne({age:25}).then(res=>{ console.log(res); }) User.countDocuments({}).then(res=>{ console.log(res); })
删除文档
-
findOneAndDelete删除一条文档
-
deleteMany删除满足条件的所有文档,会优先执行
Course.findOneAndDelete({_id:'5e4b6a5ff66c2c3270dfb415'}).then(res=>{
console.log(res);
})
Course.deleteMany({name:['课程1','课程2']}).then(res=>{
console.log(res);
})
更新文档
updateOne()修改查询到的第一个文档;参数1:修改前的值,参数2:修改后的值
updataMany()修改查询到的所有文档
Course.updateOne({_id:6154974564987},req.body).then(res=>{
console.log(res);
})
Course.updateMany({name:'测试2'},{name:'结果'}).then(res=>{
console.log(res);
})
插件
分页插件
指令:npm install mongoose-sex-page
const pagination = require('mongoose-sex-page') //User表示集合的构造函数(User) //page中的数据为查询第几页(currentPage) //size表示每一页的数据(pageSize) //dispaly表示总共显示多少页面,(total) //exec表示像数据库发送查询请求,不需要参数但是必填 pagination(User).page(1).size(20).display(8).exec() module.exports = async(req,res)=>{ const currentPage = req.query.page let articles = await pagination(Article).find({}).page(currentPage).size(3).display(3).populate('author').exec() res.send(articles) 查询到的结果 // res.render('admin/article',{ // link:'/admin/article', // articles // }) }

浙公网安备 33010602011771号