MongoDB

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

数据库相关概念

Mongoose第三方包

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

使用npm install mongoose 命令下载。

启动MongoDB-

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

数据库连接-

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

mongoose.connect('mongodb://localhost/playground')

            .then( () => console.log('数据库连接成功'))

            .catch( err => console.log('数据库连接失败', err));

创建数据库

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

创建集合

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

//设定集合规则

const courseSchema = new mongoose.Schema ({

      name : String,

      author : String,

      isPublished : Boolean

});

//创建集合并应用规则

const Course = mongoose.model('Course', courseSchema);

//course

创建文档

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

分为两步:创建集合实例,调用实例对象下的save方法将数据保存到数据库中。

//创建集合实例

const course = new Course ({

        name : 'Node.js course',

        author : String,

        tag : ['node','backend'],

        isPublished : true

});

//将数据保存到数据库中

course.save ();

Course.create({name : 'JavaScript基础', author : '黑马讲师', 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))

MongoDB数据库导入数据

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

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

查询文档

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

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

//返回文档集合

[{

    _id : 3762897299,

    name : 'node.js基础',

    author : '黑马讲师'

},{

    _id : 3762897298,

    name : 'javascript',

    author : '黑马讲师'

}]

//根据条件查找文档

Course.findOne({name : 'node.js基础'}).then(result => console.log(result));

//返回文档

{

    _id : 3762897299,

    name : 'node.js基础',

    author : '黑马讲师'

}

//匹配大于,小于

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 email').then(result => console.log(result))

//将数据按照年龄进行排序

User.find().sort('age').then(result => console.log(result))

//skip跳过多少条数据,limit限制查询数量

User.find().skip(2).limit(2).then(result => console.log(result))

删除文档

//删除单个

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

//删除多个

User.deleteMany({}).then(result => console.log(result))

更新文档

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

User.updateMany({查询条件},{要修改的值}).then(result => console.log(result))

mongoose验证

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

require:true  必传字段

minlength:3  字符串最小长度

maxlength:20  字符串最大长度

min : 2  数值最小为2

max : 100数值最大为100

enum : ['html','css','javascript','node.js']

trim : true  去除字符串两边空格

validate:自定义验证器

default: 默认值

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

集合关联

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

使用id对集合进行关联

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

集合关联实现

//用户集合

const User = mongoose.model('User', new mongoose.Schema({ name : {type : String}}));

//文章集合

const Post = mongoose.model('Post', new mongoose.Schema({

    title : { type : String},

    author : { type : mongoose.Schema.Types.ObjectId,ref:'User'}

}));

//联合查询

Post.find()

.populate('author')

.then(err,result) => console.log(result);

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容