启动mongdb net start mongdb
连接数据库:
mongoose.connect('mongodb://localhost/index') .then(()=>{console.log('连接成功')})
并不需要显示创建数据库,其中第三方模块用于对数据库的一些操作
创建集合const cousre=new mongoose.Schema({ 设定集合规则: })
注意:其实返回的是一个构造函数
使用规则创建集合
mongoose.model('course',cousres)
插入数据
const one=new course({ 要插入的数据})
对数据进行保存
course.save()
另一种创建方法:
course.create({数据},(err,result=>{ console.log(err) console.log(result) })
关于数据库的操作都是异步操作,所以支持异步函数的语法 分割线
mongdb中导入数据
mongoimport -d playground -c users --file ./user.json
playground 文件夹下的文件user ,然后是要导入文件的目录
如何查询文档
User.find(可以传入一个对象).then()
lt表示小于$in匹配包含 -前缀是不显示的字段
skip表示要跳过几条数据limit表示限制显示几条文档
删除文档
User.findoneAndDelete返回删除的文档
User.deleteMany参数为查询条件
更新文档
User.updataOne({查询条件},{要更改的值})
返回操作状态
updateMany
验证
require字段
title:{ type:String, required:ture }
min是最小值minlength是最小长度
枚举enum:['选项']
每个实例对象内的数据有自定义验证
validate:{ validator:function( )} }, message:'自定义错误信息'
集合关联
type:mongoose.Schema.Types.ObjectId, ref:'User'所关联的集合
关联实例要设置关联对应的ID Post.find().populate('author')
author字段为要查询的关联信息
数据分页
let page=req.query.page||1;
let pagesize=10;
let count=await User.countDocuments({});
let total=Math.ceil(count/pagesize);
let start=pagesize*(page-1);
let users=await User.find({}).limit(pagesize).skip(start);
第三方模块 mongoose-sex-page
const pagenation=require('mongoose-sex-page');
pagenation(Article).find().page(1).size(2).display(3).populate(author).exec
其中exec向数据库中发送请求
page表示当前页
数据库添加账号
1、运行powershell
2、连接数据库
3、show dbs查看数据库
4、 use admin
5、db.createUser()建立超级管理员和普通用户
6、创建完用户后关闭服务器
net stop mongodb
mongd remove原始的数据库连接方式移除
7、重新启动服务器,首先对log路径进行配置
8、net start mongodb启动服务器
9、在项目中,连接数据库js文件中填写登录信息mongoose.connect(mongoose://itcast:itcast@localhost/blog)
@前内容为用户名,和密码