MongoDB学习记录

通过node安装mongoose模块,进行mongodb的一些基本语法操作。

一、启动mongodb

在命令行中输入net start mongoDB

二、安装mongoose

npm install mongoose

三、新建demo.js,输入下列代码

// 引入mongoose
const mongoose = require('mongoose')
// 连接mongodb数据库
mongoose.connect('mongodb://localhost/demoDatabase')
.then(res=>{
    console.log('连接成功')
}).catch(err=>{
    console.log('连接失败')
})

上面代码完成后悔出现一个警告

(node:11972) 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.

上列代码加入一个对象{ useUnifiedTopology: true }

// 引入mongoose
const mongoose = require('mongoose')
// 连接mongodb数据库
mongoose.connect('mongodb://localhost/demoDatabase',{ useUnifiedTopology: true })
.then(res=>{
    console.log('连接成功')
}).catch(err=>{
    console.log('连接失败')
})

四、创建集合规则

const Course = new mongoose.Schema({
    name:String,
    author:String,
    sex:String
})

五、插入文档

第一种插入文档方式:

const course = new Course({
  name:'html',
  author:'张三',
  sex:'男'
})
course.save()

第二种插入文档方式通过回调函数获取异步api的返回值:

Course.create({ name:'html',author:'张三',sex:'男'},(err,result)=>{
    // 如果err返回为null 说明插入文档成功
    if(err !== null){
        return console.log('失败:',err);
    }
    console.log('成功:',result)
})

第三种方式使用promise异步接收返回值:

Course.create({ name:'html',author:'张三',sex:'男'})
.then(result => {
  console.log('成功:',result);
}).catch(err => {
  console.log('失败:',err);
})

六、mongoDB数据库导入数据

首先在官网下载MongoDB Database Tools,下载完成后解压出来,将压缩包里面bin里的exe文件,全部复制到mongoDB安装目录,我的是C:\Program Files\MongoDB\Server\4.4\bin,然后配置系统环境变量,依次点开此电脑——属性——高级系统设置——环境变量——在系统变量中找到Path双击——新建——将路径复制进去——确定
导入命令:
mongoimport -d 数据库名称 -c 集合名称 --file 要导入的数据文件
例:
mongoimport -d playground -c users --file .\user.json

七、查询文档

// 新建集合规则 userSchema 
const userSchema = new mongoose.Schema({
  name: String,
  age: Number,
  emial: String,
  password: String,
  hobbies: [String]
})
// 使用规则创建集合
const User= mongoose.model('User', userSchema);

1.0、find()方法查询用户集合中的所有文档
User.find().then(result => console.log(result));
1.1、find()方法查询指定_id查询文档数据
User.find({ _id: '5c09f267aeb04b22f8460968' }).then(result => console.log(result));
注意:通过find()方法查询出来的数据,不管是多少条返回的都是数组
1.2、findOne()方法返回一条文档数据,默认返回当前集合中的第一条文档,返回一个对象
User.findOne().then(result => console.log(result));
1.3、findOne()通过指定name查询文档数据,返回一个对象
User.findOne({ name: '张三' }).then(result => console.log(result));
1.4、匹配查询 大于 小于,查询年龄大于10小于20以内的文档数据,gt:大于,lt:小于
User.find({ age: { $gt: 10, $lt: 20 } }).then(result => console.log(result));
1.5、匹配包含,查询爱好中包含'打豆豆'的文档数据
User.find({ hobbies: { $in: ['打豆豆'] } }).then(result => console.log(result));
1.6、模糊查询name中含有'王'的文档数据
User.find({ name: { $regex: '王', $options: 'i' } }).then(result => console.log(result));
1.7、选择要查询的字段并且不查询_id的文档数据
User.find().select('name age -_id').then(result => console.log(result));
1.8、将年龄按照升序进行排序,降序则修改为-age
User.find().sort('age').then(result => console.log(result));
1.9、查询跳过一条并且限制3条的文档数据,skip跳过多少条数据 limit限制查询数量
User.find().skip(1).limit(3).then(result => console.log(result));

八、删除文档

1.0、删除指定_id的文档数据,成功则返回被删除的对象,没找到则返回null,删除单个文档数据
User.findOneAndDelete({ _id: '5c09f267aeb04b22f8460968' }).then(result => console.log(result));
1.1、删除多个文档数据,将数据库中的文档全部删除,返回ok为1则代表删除成功
User.deleteMany({}).then(result => console.log(result));

九、更新文档

1.0、更新指定name的文档数据,王二麻子更新为王麻子返回ok为1则代表更新成功,(更新一个)
User.updateOne({ name: '王二麻子' }, { name: '王麻子' }).then(result => console.log(result));
1.1、更新文档中所有数据,将全部文档password更新为123,(更新多个)
User.updateMany({}, { password: '123' }).then(result => console.log(result));

十、mongoDB验证

// 新建集合规则 userSchema 
const userSchema = new mongoose.Schema({
  // 标题
  title: {
    // 类型
    type: String,
    // 必填项
    required: [true, '标题不能为空'],
    // 最小长度
    minlength: [3, '最小长度不能低于3'],  //字符串长度
    // 最大长度
    maxlength: [15, '最大长度不能高于15'],  //字符串长度
    // 去除两端空格
    trim: true
  },
  // 年龄
  age: {
    type: Number,
    // 最小值
    min: [18, '最小数组不能低于18'],
    // 最大值
    max: [100, '最大数组不能高于100']
  },
  // 日期
  dateTime: {
    type: Date,
    // 默认值
    default: Date.now
  },
  // 分类
  category: {
    type: String,
    // 指定分类传入html、css、javascript、vue,传入其他则报错
    // enum: ['html', 'css', 'javascript', 'vue']
    enum: {
      values: ['html', 'css', 'javascript', 'vue'],
      message: '当前没有找到该分类标签'
    }
  },
  // 作者
  author: {
    type: String,
    // 自定义验证
    validate: {
      validator: v => {
        // v 要验证的值
        // 当前函数返回布尔值,true验证成功,false验证失败
        return v && v.length > 4
      },
      message: '传入的值不能为空并且不能小于4'
    },
  }
})
// 使用规则创建集合
const User= mongoose.model('User', userSchema);

十一、集合关联

// 使用规则创建集合
const User = mongoose.model('User', new mongoose.Schema({
  name: {
    type:String,
    unique:true  // 表示唯一键
  },
  age: Number,
  emial: String,
  password: String,
  hobbies: [String]
}));
// 使用规则创建集合
const Course = mongoose.model('Course', new mongoose.Schema({
  title: String,
  author: {
    // 使用id将当前集合和用户集合关联
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },
  isPublished: Boolean
}));

// 创建课程
Course.create({ title: 'java', author: '5c09f294aeb04b22f8460969' }).then(result => console.log(result));

// 使用populate方法进行关联集合查询
// 查询Course集合中所有关联author信息的文档数据
Course.find().populate('author').then(result => {
  // 循环查询出来的文档数据
  for (let item of result) {
    console.log(item);
  }
})
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。