MongoDB数据库

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

1.1为什么要使用数据库

  • 动态网站中的数据都是存储在数据库中的

  • 数据库可以用来持久存储客户端通过表单收集的用户信息

  • 数据库软件本身可以对数据进行高效的管理

1.2什么是数据库

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

 

 

 

 

 

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第3三方包

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

  • 使用npm install mongoose命令下载

1.7启动MongoDB

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

1.8数据库连接

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

MongoDB返回的是promise对象

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

连接数据库时如果提示如下信息,在content方法里面添加第二个参数, { useNewUrlParser: true }

(node:15596) 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:14524) 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');
// 1、连接数据库playground,如果没有此数据库,系统会自动创建
mongoose.connect('mongodb://localhost/playground', {
       useUnifiedTopology: true,
       useNewUrlParser: true
  })
   // 连接成功
  .then(() => console.log('数据库连接成功'))
   // 连接失败
  .catch(err => console.log(err, '数据库连接失败'));

1.9 创建数据库

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

posted @ 2020-11-08 17:39  清出于兰  阅读(156)  评论(0编辑  收藏  举报