MongoDB数据库的使用与学习

1. MongoDB数据库安装

1.下载地址:https://www.mongodb.com/download-center/community
2. 相关概念:

  • collection—集合,一组数据的集合,可看作Js中的数组
  • document—文档,一条具体的数据,可看作Js中的对象
  • field—字段,文档中的属性名,可看作对象中的属性名

3. 需要依赖的包: Mongoose =>命令行中的下载命令—npm install Mongoose

2. MongoDB的连接与创建

1. 启动MongoDB(以管理员身份运行命令行,在命令行中输入 net start mongoDB)
命令行操作
2. 创建与连接数据库

// 引入第三方模块mongoose,用于操作数据库
const mongoose = require('mongoose');

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

3. MongoDB中创建集合和文档以及导入数据

1.创建集合
创建集合之前需要设定集合的规则,再通过mongoose.model()创建集合,示例代码如下:

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

// mongoose.model()的返回值是一个构造函数 一个参数是集合名称,第二个参数是集合规则
const Course = mongoose.model('Course', courseSchema); // 在数据库中集合实则为courses

2.创建文档
因为mongoose.model()返回的是一个构造函数,因而只需要将集合实例化即可创建文档,在创建文档后将文档存入数据库,数据库中才会存在相应的数据;还有另一种方法则是则是通过.create()方式实现,代码如下:

// 实例化构造函数创建文档
const course = new Course({
    name: 'node.js',
    author: 'lxz',
    isPublished: true
});
// 将文档信息传入数据库
course.save();
/********************第二种方法*****************/
/**
 * mongoose支持两种获取异步API结果的方式
 * 一种是回调函数
 * 另一种是Promise对象
 */
// 在集合中插入文档的另一种方式
// 获取异步API结果------回调函数
/* Course.create({ name: 'javaScript', author: 'lxz', isPublished: false }, (err, res) => {
    console.log(err);
    console.log(res);
}); */
// 获取异步API结果------promise对象
Course.create({ name: 'html', author: 'lxz', isPublished: false })
    .then(result => console.log(result))
    .catch(err => console.log(err))

3.导入数据
使用(mongoimport -d 数据库 -c 集合 --file 文件路径)命令对数据进行导入,而要使用mongoimport则需要将其应用程序所在的目录添加到系统的环境变量中才能使用,否则会报错。

4. MongoDB的删改查

1. 查询文档
查询有两种方法:find()和findOne() 其返回的都是promise对象,而promise的讲解在之前已经有所介绍—异步编程中的promise,而这两种方法的使用将通过代码呈现。

/**********************下列为查询数据库文档中常用的方法*********************/

// find() 方法的数组可以是多个  当find()中没有参数时默认查找所有文档  []形式
// User.find().then((result) => console.log(result));

// 通过条件进行查找
// User.find({ name: '张三' }).then(result => console.log(result));

// findone()方法返回一条文档 没有参数时默认返回第一条文档  {}形式
// User.findOne({ _id: '5c09f267aeb04b22f8460968' }).then(res => console.log(res));

// 查询年龄大于20小于40的文档
// User.find({ age: { $gt: 20, $lt: 40 } }).then(res => console.log(res));

// 匹配包含'足球'的文档   实际开发可用于网站搜索中关键字的检索使用
// User.find({ hobbies: { $in: '足球' } }).then(res => console.log(res));

// 选择要查询的字段,多个字段间以空格隔开  如若不想查询某字段在其前面加'-'
// User.find().select('name age -_id').then(res => console.log(res));

// 使用sort()对筛选数据进行升序排列如:sort('age')  降序则是:sort('-age')
// User.find().select('name age').sort('age').then(res => console.log(res));

// skip()跳过前几个数据 limit()限制查询的数量  实际开发中用于分页功能
User.find().select('name age -_id').sort('-age').skip(1).limit(3).then(res => console.log(res));

2. 删除文档
删除文档也有两种方法:findOneAndDelete()以及deleteMany()

/**********************下列为删除数据库文档中常用的方法*********************/

// 查询并删除单个文档  如若查询结果为多个,则删除第一个文档  其返回值为被删除的文档
// User.findOneAndDelete({ _id: '5c09f267aeb04b22f8460968' }).then(res => console.log(res));

// 删除满足查询条件的多个文档,当参数为空时删除所有文档 其返回值为一个对象形式:{n: 5,ok: 1,deletedCount: 5}
User.deleteMany({}).then(res => console.log(res));

3.更新文档
更新文档的方法有两种:updateOne()和updateMany()

/**********************下列为更新数据库文档中常用的方法*********************/

// updateOne()更新单个文档,第一个参数为要查询的条件,第二个参数为要修改的值
// User.updateOne({ name: '李四' }, { name: 'lxz', age: 22 }).then(res => console.log(res));

// updateMany()更新多个文档,参数与updateOne()一致,不同的是第一个参数为空时,查询的是全部数据
User.updateMany({}, { age: 22 }).then(res => console.log(res));

5. MongoDB的规则验证

在创建集合规则的时候可以设置每个字段的验证规则,只有满足验证条件才能将数据插入,否则插入失败(可用 error.errors[‘字段名’].message 在控制台中输出)
而规则中常用的关键字有以下:

  • required:true                 必传字段
  • maxlength:10                字符串最大长度为10
  • minlength:2                 字符串最小长度为2
  • min:2                   数值最小值为2
  • man:10                   数值最大值为10
  • enum:[‘a’,‘b’,‘c’,‘d’]              枚举,传入值必须包是数组中的数值
  • default:默认值                设置当不传入时的默认值
  • trim:true                  去除字符串两边的空格
  • validate: validator(){}              自定义验证器
  • unique:true                 保证数据的唯一性,有重复则插入失败
/*********************相关使用方法如下****************************/
// 引入第三方模块mongoose
const mongoose = require('mongoose');
// 通过mongoose连接数据库
mongoose.connect('mongodb://localhost/demo', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => console.log("数据库连接成功"))
    .catch(err => console.log(err, "数据库连接失败"));

// 设定集合规则
const testSchema = new mongoose.Schema({
    name: {
        type: String,
        // 必传字段
        required: true, // 可定义错误时的信息,形如:[true,'name为必传字段']
        minlength: [3, '最小长度为3'], // 可定义错误时的信息,形如:[3,'最小长度为3']
        maxlength: 6, // 可定义错误时的信息,形如:[6,'最大长度为6']
        // 去掉字符串两边空格
        trim: true
    },
    age: {
        type: Number,
        // 数值型的最大值和最小值,也能够自定义错误信息,形如:[18,'传入的最小值为18']
        min: 18,
        max: 100
    },
    date: {
        type: Date,
        // 设置默认值,即没有设置该项时,默认为该值
        default: Date.now
    },
    category: {
        type: String,
        // 枚举 输入的值必须包括在数组中,否则将会报错
        enum: {
            values: ['html', 'css', 'javascript'],
            message: '输入的值不在范围内' // 错误信息
        }
    },
    other: {
        type: String,
        // 自定义验证器
        validate: {
            // 该函数返回的是布尔值、true为成功false为失败、v代表输入的值
            validator: v => v && v.length > 3,
            // 设置错误信息
            message: '传入的值不符合规则'
        }
    }
});
// 创建一个集合(实例化方法)
const Test = mongoose.model('Test', testSchema); // 对应demo数据库中的集合应该是tests

Test.create({ name: 'lxz', age: 22, category: 'c++', other: 'hhh' })
    .then(res => console.log(res))
    .catch(err => {
        // 获取控制台的所有错误信息
        const errs = err.errors;
        // 对所有错误信息进行遍历
        for (var attr in errs) {
            // 在控制台中输出错误信息
            console.log(errs[attr]['message']);
        }
    });

6. MongoDB集合关联

不同的集合之间若是存在着一定的关系,如登录的用户名既可用于登录又是发表文章之时的作者的名称,则需要用到集合关联。
如何进行集合关联:

  • 使用id对集合进行关联
  • 使用populate()进行关联集合查询

具体代码如下:

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

// 创建集合 在数据库中集合名为users
const User = mongoose.model('User', new mongoose.Schema({ name: { type: String, required: true } }));

// 创建集合 在数据库中集合名为tests
const Test = mongoose.model('Test', new mongoose.Schema({ title: { type: String }, name: { type: mongoose.Schema.Types.ObjectId, ref: 'User' } }));

// 创建文档
// User.create({ name: 'student' }).then(res => console.log(res));
// 先执行上一步获取其_id存入name中
// Test.create({ title: 'abc', name: '5e466b991b41722064b20562' }).then(res => console.log(res));

// 联合查询 name为Test中的name
Test.find().populate('name').then(res => console.log(res)).catch(err => console.log(err));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值