初试MongoDB

Author Avatar
Klein 8月 01, 2018

你好,MongoDB。

安装与准备

由于电脑用的 win7,并考虑到版本的稳定性问题。并未使用最新的 MongoDB4.0,而是mongodb-win32-x86_64-2008plus-ssl-3.4.1-signed。

下载对应版本,并安装。

在 choose setup type 这一步的时候,如果选择 Complete 会直接默认安装到默认的C盘,而如果选择 Custom,就可以自定义安装路径。

在任意目录下创建两个文件夹:

  • 数据库路径(data 目录)
  • 日志路径(logs 目录)
  • 配置路径(etc 目录)
    在日志路径下新建日志文件(mongo.log 文件)
    在配置路径下新建配置文件(mongo.conf 文件)

初次运行

1
2
3
4
5
6
7
# 切换到安装目录下的 bin 文件夹
d:
cd "Program Files\MongoDB\Server\3.4\bin"

# 启动
# --dbpath 后面的参数是你自己刚才新建的数据库路径
mongod --dbpath D:\MongoDB\data

然后启动浏览器打开 http://127.0.0.1:27017 如有有行英文:It looks like you are trying to assess MongoDB over HTTP on the native drive port,那就说明已经启动成功了。

基础配置

虽然已经连接成功,但是每次这样实在是太麻烦了。所以需要进行一些配置。

打开配置路径下的 mongo.conf 文件,进行配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#数据库路径  
dbpath=D:\MongoDB\data
#日志输出文件路径
logpath=D:\MongoDB\logs\mongo.log
#错误日志采用追加模式
logappend=true
#启用日志文件,默认启用
journal=true
#这个选项可以过滤掉一些无用的日志信息,若需要调试使用请设置为false
quiet=true
#端口号 默认为27017
port=27017
#http 配置
httpinterface=true

打开命令行运行:

1
2
3
4
5
6
7
# 切换到安装目录下的 bin 文件夹
d:
cd "Program Files\MongoDB\Server\3.4\bin"

# 启动
# --config 后面的参数是你自己的配置文件
mongod --config "D:\MongoDB\mongo.conf"

启动浏览器打开 http://127.0.0.1:27017 ,还是那行英文。

开启 interface 页面

1
mongod --config "D:\MongoDB\mongo.conf" --httpinterface

打开 http://127.0.0.1:28017 ,即可打开 interface 页面。

如果觉得麻烦,可以在配置文件中加上这项配置:

1
2
#http 配置
httpinterface=true

配置完后直接启动,不需要加刚才的选项照样可以开启interface 页面:

1
mongod --config "D:\MongoDB\mongo.conf"

再次打开 http://127.0.0.1:28017 ,可以正常访问 interface 页面:

创建并启动MongoDB服务

1
2
3
4
5
# 创建 MongoDB 服务
mongod --config "D:\Mongo\mongo.conf" --install --serviceName "MongoDB"

# 启动 MongoDB 服务
net start MongoDB

在使用 --install --serviceName "MongoDB" 创建服务后,可以在控制面板的本地服务中看到该服务,并且处于未开启状态,所以可以手动开启,也可以使用net start MongoDB开启。

添加环境变量

将 MongoDB 安装目录下的 bin 文件夹的路径添加到系统环境变量的 path 变量,切记,在加之前在前面加有个分号;和别的环境变量区分。

添加了环境变量以后,就可以直接输入mongo启动,而不用切换到安装目录下,再输入mongo启动。

使用 mongo VUE

报错

  • URL string parser
    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.

大致意思是连接mongodb数据库的链接解析器会在未来移除,要使用新的解析器,通过配置{ useNewUrlParser:true }来连接。

mongoose.connect(“mongodb://username:password@localhost:27017/dbname”, { useNewUrlParser: true })