nodejs - MongoDB

1. 数据库概述及环境搭建

1.1 为什么要使用数据库

  • 动态网站中的数据都是存储在数据库中的
  • 数据库可以用来持久存储客户端通过表单收集的用户信息
  • 数据库软件本身可以对数据进行高效的管理

http://localhost/article?id=1

http://localhost/article?id=2

通过传递不同参数请求进行处理,显示不同数据结果

1.2 什么是数据库

数据库即存储数据的仓库,可以将数据进行有序的分门别类的存储。它是独立于语言之外的软件,可以通过API去操作它。

常见的数据库软件有:mysql、mongoDB、oracle。

​ nodejs可以使用多种数据库,本次采用mongoDB作为数据库,因为mongoDB开放的api也是JavaScript的语法,对nodejs也是一样的,mongoDB存储的数据是JSON格式的,学习mongoDB对nodejs比较友好。

1.3 MongoDB数据库下载安装

下载地址:https://www.mongodb.com/download-center/community

1.4 MongoDB可视化软件

MongoDB可视化操作软件,是使用图形界面操作数据库的一种方式。

1.5 数据库相关概念

在一个数据库软件中可以包含多个数据仓库,在每个数据仓库中可以包含多个数据集合,每个数据集合中可以包含多条文档(具体的数据)。

术语 解释说明
database 数据库,mongoDB数据库软件中可以建立多个数据库
collection 集合,一组数据的集合,可以理解为JavaScript中的数组
document 文档,一条具体的数据,可以理解为JavaScript中的对象
field 字段,文档中的属性名称,可以理解为JavaScript中的对象属性

1.6 Mongoose第三方包

  • 使用Node.js操作MongoDB数据库需要依赖Node.js第三方包mongoose

  • 使用npm install mongoose命令下载

1.7 启动MongoDB

在命令行工具中运行net start mongoDB即可启动MongoDB,否则MongoDB将无法连接。

停止服务:net stop mongoDB

注:如果出现拒绝访问,权限不够,请用管理模式打开命令行工具

1.8 数据库连接

使用mongoose提供的connect方法即可连接数据库。

//引入mongoose模块
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground')
     .then(() => console.log('数据库连接成功'))
     .catch(err => console.log('数据库连接失败', err));

说明:

  1. 在MongoDB中不需要显式创建数据库,如果正在使用的数据库不存在,MongoDB会自动创建

  2. 使用当前连接会提示错误警告:

    (node:9688) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
    (node:9688) 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.

    两句话大概意思:当前URL字符串分析器与当前服务器发现和监视引擎已弃用,将在将来的版本中删除。

在连接方法添加如下参数解决报错警告:

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

2. MongoDB增删改查操作

2.1 创建集合

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

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

//创建集合并应用规则
const Course = mongoose.model('Course',courseSchema);//courses
  1. 集合名称规范首字母大写,如:Course
  2. mongoose自动创建的集合不会以首字母大写形式存在,而是小写字母后面加s,如:courses
  3. model方法返回构造一个函数,该构造函数代表一个集合
  4. 默认创建集合不会马上创建,而是插入数据时为空才自动创建。

2.2 创建文档

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

分为两步:

  1. 创建集合实例。

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

//创建集合实例
const course = new Course({
    name:'NodeJs精品课',
    author:'Mr li',
    isPublished:true
});
//将数据保存到数据库
course.save();

另外一种方式(有回调函数):

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

Course.create({name: 'JavaScript基础', author: '黑马讲师', isPublish: true})
      .then(doc => console.log(doc))
      .catch(err => console.log(err))

注意:所有对数据库操作都是异步操作

3.3 mongoDB数据库导入数据

找到mongodb数据库的安装目录,将安装目录下的bin目录放置在环境变量中。

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

3.4 查询文档

//  根据条件查找文档(条件为空则查找所有文档)
Course.find().then(result => console.log(result))

返回数据:

[
  {
    _id: 5e70cd0fa25bbf21c0077aca,
    name: 'NodeJs精品课',
    author: 'Mr li',
    isPublished: true,
    __v: 0
  },
  {
    _id: 5e70cf6b0e954a332c9810a2,
    name: 'JavaScript基础',
    author: 'Mr li',
    isPublished: true,
    __v: 0
  }
]
//查找指定Id的数据
Course.find({_id: '5e70cf6b0e954a332c9810a2'}).then(result => console.log(result));

返回数据

[
  {
    _id: 5e70cf6b0e954a332c9810a2,
    name: 'JavaScript基础',
    author: 'Mr li',
    isPublished: true,
    __v: 0
  }
]

使用find方法查找的数据不管多少条都是返回数组格式,0条返回空数组

//  根据条件查找文档
Course.findOne({_id: '5e70cf6b0e954a332c9810a2'}).then(result => console.log(result))

返回数据

  {
    _id: 5e70cf6b0e954a332c9810a2,
    name: 'JavaScript基础',
    author: 'Mr li',
    isPublished: true,
    __v: 0
  }

findOne方法只返回一条数据,为json对象格式

//匹配大于 小于
User.find({age:{$gt:20,$lt:50}}).then(result=>console.log(result));

//匹配包含
User.find({hobbies:{$in:'敲代码'}}).then(result=>console.log(result));

//选择要查询的字段
User.find().select('name age').then(result=>console.log(result));
//注意:默认还会有_id,如果不想显示某个字段可以添加-,表示过滤字段,如:-_id

//将数据按照年龄进行排序,升序
User.find().sort('age').then(result=>console.log(result));
//说明:降序在字段前面加-,如:-age

//skip 跳过多少条数据  limit 限制查询数量
User.find().skip(3).limit(3).then(result=>console.log(result));

3.5 删除文档

//删除查找第一个对象,并返回删除的对象
User.findOneAndDelete({}).then(result=>console.log(result));
//删除多个,条件为空删除全部,返回删除结果与个数
User.deleteMany({}).then(result=>console.log(result));

3.6 更新文档

// 更新单个
User.updateOne({查询条件}, {要修改的值}).then(result => console.log(result))

// 更新多个
User.updateMany({查询条件}, {要更改的值}).then(result => console.log(result))

3.7 mongoose验证

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

  • required: true 必传字段
  • minlength:3 字符串最小长度
  • maxlength: 20 字符串最大长度
  • min: 2 数值最小为2
  • max: 100 数值最大为100
  • enum: ['html', 'css', 'javascript', 'node.js'] 枚举,列举可用项,如果不是枚举范围中就会报错
  • trim: true 去除字符串两边的空格
  • validate: 自定义验证器
  • default: 默认值

获取错误信息:error.errors['字段名称'].message

示例

// 创建集合规则
const PostSchema = new mongoose.Schema({
    title:{
        type:String,
        required:[true,'文章内容不能为空'],
        minlength:[2,'文章内容不能小于2个字'],
        maxlength:[10,'文章内容不能大于10个字'],
        //去除字符串两边的空格
        trim:true
    }
});
const Post = mongoose.model('Post',PostSchema);
Post.create({title:'123'}).then(result => console.log(result));

说明:验证规则可以传递单个项或者数组,第二个值为自定义错误信息

自定义验证规则,并处理错误信息

const PostSchema = new mongoose.Schema({
    title:{
        type:String,
        required:[true,'文章内容不能为空'],
        minlength:[2,'文章内容不能小于2个字'],
        maxlength:[10,'文章内容不能大于10个字'],
        //去除字符串两边的空格
        trim:true
    },
    author:{
        type:String,
        validate:{//自定义验证规则
            validator: v =>{
                //返回布尔值,true验证成功,false验证失败,v为需要验证的值
                return v && v.length > 4
            },
            //自定义错误
            message: '输入的值不匹配'
        }
    }
});
const Post = mongoose.model('Post',PostSchema);
Post.create({title:'123',author:''}).then(result => console.log(result))
.catch(error => {
    //获取信息错误对象
    const errors = error.errors;
    //循环错误对象
    for(attr in errors){
        //将错误信息打印
        console.log(errors[attr].message);
    }
});

3.8 集合关联

通常不同集合的数据之间是有关系的,例如文章信息和用户信息存储在不同集合中,但文章是某个用户发表的,要查询文章的所有信息包括发表用户,就需要用到集合关联。

  • 使用id对集合进行关联

  • 使用populate方法进行关联集合查询

// 用户集合
const User = mongoose.model('User', new mongoose.Schema({ name: { type: String } })); 
// 文章集合
const Post = mongoose.model('Post', new mongoose.Schema({
    title: { type: String },
    // 使用ID将文章集合和作者集合进行关联
    author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}));
//联合查询
Post.find()
      .populate('author')
      .then((err, result) => console.log(result));

猜你喜欢

转载自www.cnblogs.com/royal6/p/12527415.html
今日推荐