关于MongoDB基础使用

基本需要在超级管理权限下运行,所有可以在文件夹按住shift时,点击鼠标右键开启。
点击在此处开启PowerShell窗口

net start mongodb 开启数据库

net stop mongoDB 关闭数据库

const mongoose =require('mongoose');

mongoose.connect('mongodb://localhost/playground',{ useUnifiedTopology: true,useNewUrlParser: true })
  .then(()=>console.log('数据库连接成功了'))
  .catch(err=>console.log(err,'数据库连接失败了'))

一般要在超级权限下开启

MongoDB增删改查

3.1创建集合

创建集合分为两步,一是对集合设定规则,二是创建集合,创建mongoose.Schema构造函数的实例即可

//引入mongoose 第三方模块 用来操作数据库
const mongoose =require('mongoose');
// 连接数据库
mongoose.connect('mongodb://localhost/playground',{ useUnifiedTopology: true,useNewUrlParser: true })
  .then(()=>console.log('数据库连接成功了'))
  .catch(err=>console.log(err,'数据库连接失败了'))

//设定集合规则
const courseSchema =new mongoose.Schema({
  name:String,
  author:String,
  isPublished:Boolean
});

// 创建集合并应用规则 model的第一个参数首字母大写
const Course=mongoose.model('Course',courseSchema) //在数据库里courses多了个s
3.2创建文档

在可视化里看不到创建的数据库 是因为没有数据

需要创建文档实际上就是向集合里插入数据

1.创建集合实例

2.调用实例对象下的save方法将数据保存到数据库中

//创建集合实例
const course=new Course({
  name:'Node.js course',
  author:'杨大师',
  tags:['node','backend'],
  isPublished:true
})
//调用save方法保存到数据库中
course.save();

除了上面,还有一个create方法可以插入数据

Course.create({
  name:'JavaScript基础',
  author:'老z',
  isPublished:false
},(err,doc)=>{
  // 错误对象
  console.log(err);
  // 当前插入的文档
  console.log(doc);
})

*****输出*****
数据库连接成功了
null	//无err  报null
{
  _id: 60a74d72b3e0f436d0e87fdc,
  name: 'JavaScript基础',
  author: '老z',
  isPublished: false,
  __v: 0
}

除了上面这个写法,还可以将它写为下面这种形式,这是Promise的格式,说明这是一个异步操作

以后主要也是使用Promise对象的方式

Course.create({name:'高数',author:'舞舞舞'})
      .then(doc=>console.log(doc))
      .catch(err=>console.log(err))
3.3 MongoDB数据库导入数据

mongoimport -d 数据库名称 -c 集合名称 -file要导入的的数据文件

启用mongoimport 需要先将MongoDB数据库的安装目录中的bin文件夹绑定到环境变量下的path目录

在这里我是放在

D:\MongoDB\Server\4.4\mongodb-database-tools-windows-x86_64-100.2.1\bin

把这个复制黏贴到Path中

举例 -d 就是database 导入到哪个数据库当中 -c就是导入到哪个集合当中

在终端  输入 mongoimport -d playground -c users --file ./user.json
3.4查询文档

在查询文档时,依旧需要保持数据库连接,以及创建集合等要求。

//根据文件查找文档(条件为空则查询所有文档)

Course.find().then(result => console.log(result))

*****返回*****
[
  {
    _id: 60a74adb02ef5018d02f3759,
    name: 'Node.js course',
    author: '杨大师',
    isPublished: true,
    __v: 0
  },
  {
    _id: 60a74d3816df5831845a9ba9,
    tags: [],
    name: 'JavaScript基础',
    author: '老狗',
    isPublished: false,
    __v: 0
  },
  { _id: 60a74e1b0f9daf3b40a195c6, name: '高数', author: '舞舞舞', __v: 0 }
]

在find()方法里面可以设定查询某个对象,返回的是数组

User.find({_id:'5c09f267aeb04b22f8460968'}).then(result=>console.log(result))

用findone()方法查找的是一个对象 不输参数的话,默认返回第一条文档

User.findOne({_id:'5c09f267aeb04b22f8460968'}).then(result=>console.log(result))

匹配大于 g t 小 于 gt 小于 gtlt

User.find({age:{$gt:20,$lt:50}}).then(result=>console.log(result))

匹配包含 $in

User.find({hobbies:{$in:['敲代码']}}).then(result=>console.log(result))

选择要查询的字段 返回内容会出现__id 如果不想查询某个默认字段 可以在该字段前加个 - 例如

-_id

User.find().select('name email -_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(2).limit(3).then(result=>console.log(result))
3.5 删除文档

删除单个

Course.findOneAndDelete({}).then(result=>console.log(result))

删除多个

Course.deleteMany().then(result=>console.log(result))
3.6更新文档
User.updateOne({查询条件},{要修改的值}).then(result=>console.log(result))
//更新单个
User.updateOne({name:'张三'},{name:'杨老二'}).then(result=>console.log(result))
//更新多个
User.updateMany({},{age:56}).then(result=>console.log(result))
 
3.7 mongoose验证

在创建集合规则,可以设置当前字段的验证规则,验证失败则插入失败

请添加图片描述

打印错误信息

Post.create({   title:   666 ,category:'123',age:55, author:'db'})
    .then(result=>console.log(result))
    .catch(error=>
      {
        //获取错误信息对象
        const err=error.errors;
        //循环错误信息对象
        for(var attr in err){
          //将错误信息打印到控制台中
          console.log(err[attr]['message']);
        }
      })

注:本文仅作为自己学习的经验日志…如若侵权,联系即删。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值