mongodb数据库

mongodb与mongoose

安装

brew install mongodb

下载安装很简单,不多说,但如果下载源是官网的话会慢很多甚至下载不成功,所以我去修改了我的homebrew源,使用的中科大镜像源。

修改方法

启动运行mongodb

刚开始如果直接在终端mongod的话基本都会报错,原因是没有找到data/db这个文件,因为默认文件路径是这个,所以我们要移动到系统根目录下cd /然后创建文件mkdir -p data/db,但是还不够,我们要添加环境变量这让我们在终端的任何地方都可以使用mongod的命令行: vim ~/.zshrc 因为我是zsh用户,所以直接编辑zshrc文件,在里面添加export PATH=/usr/local/mongodb/bin:$PATH 保存退出就好,最后记得source ~/.zshrc一下,然后就可以启动我们的mongodb了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
~ mongod
2019-08-07T19:31:12.795+0800 I CONTROL [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'
2019-08-07T19:31:12.835+0800 I CONTROL [initandlisten] MongoDB starting : pid=66667 port=27017 dbpath=/data/db 64-bit host=chenzhuodeMBP.lan
2019-08-07T19:31:12.835+0800 I CONTROL [initandlisten] db version v4.0.3
2019-08-07T19:31:12.835+0800 I CONTROL [initandlisten] git version: 7ea530946fa7880364d88c8d8b6026bbc9ffa48c
2019-08-07T19:31:12.835+0800 I CONTROL [initandlisten] allocator: system
2019-08-07T19:31:12.835+0800 I CONTROL [initandlisten] modules: none
2019-08-07T19:31:12.835+0800 I CONTROL [initandlisten] build environment:
2019-08-07T19:31:12.835+0800 I CONTROL [initandlisten] distarch: x86_64
2019-08-07T19:31:12.835+0800 I CONTROL [initandlisten] target_arch: x86_64
2019-08-07T19:31:12.835+0800 I CONTROL [initandlisten] options: {}
2019-08-07T19:31:12.837+0800 I STORAGE [initandlisten] wiredtiger_open config: create,cache_size=3584M,session_max=20000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),statistics_log=(wait=0),verbose=(recovery_progress),
2019-08-07T19:31:13.323+0800 I STORAGE [initandlisten] WiredTiger message [1565177473:323554][66667:0x1152525c0], txn-recover: Set global recovery timestamp: 0
2019-08-07T19:31:13.366+0800 I RECOVERY [initandlisten] WiredTiger recoveryTimestamp. Ts: Timestamp(0, 0)
2019-08-07T19:31:13.409+0800 I CONTROL [initandlisten]
2019-08-07T19:31:13.409+0800 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
2019-08-07T19:31:13.409+0800 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
2019-08-07T19:31:13.409+0800 I CONTROL [initandlisten]
2019-08-07T19:31:13.409+0800 I CONTROL [initandlisten] ** WARNING: This server is bound to localhost.
2019-08-07T19:31:13.409+0800 I CONTROL [initandlisten] ** Remote systems will be unable to connect to this server.
2019-08-07T19:31:13.409+0800 I CONTROL [initandlisten] ** Start the server with --bind_ip <address> to specify which IP
2019-08-07T19:31:13.409+0800 I CONTROL [initandlisten] ** addresses it should serve responses from, or with --bind_ip_all to
2019-08-07T19:31:13.409+0800 I CONTROL [initandlisten] ** bind to all interfaces. If this behavior is desired, start the
2019-08-07T19:31:13.409+0800 I CONTROL [initandlisten] ** server with --bind_ip 127.0.0.1 to disable this warning.
2019-08-07T19:31:13.409+0800 I CONTROL [initandlisten]
2019-08-07T19:31:13.409+0800 I CONTROL [initandlisten]
2019-08-07T19:31:13.409+0800 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000
2019-08-07T19:31:13.418+0800 I STORAGE [initandlisten] createCollection: admin.system.version with provided UUID: 0f3360cb-eb57-4d52-a7eb-a9e0097f4116
2019-08-07T19:31:13.465+0800 I COMMAND [initandlisten] setting featureCompatibilityVersion to 4.0
2019-08-07T19:31:13.473+0800 I STORAGE [initandlisten] createCollection: local.startup_log with generated UUID: 80abc387-e986-4779-af9a-ab07b71d7624
2019-08-07T19:31:13.517+0800 I FTDC [initandlisten] Initializing full-time diagnostic data capture with directory '/data/db/diagnostic.data'
2019-08-07T19:31:13.522+0800 I NETWORK [initandlisten] waiting for connections on port 27017
2019-08-07T19:31:13.522+0800 I STORAGE [LogicalSessionCacheRefresh] createCollection: config.system.sessions with generated UUID: c812a964-a9ff-42bc-8897-24d87db0c61e
2019-08-07T19:31:13.603+0800 I INDEX [LogicalSessionCacheRefresh] build index on: config.system.sessions properties: { v: 2, key: { lastUse: 1 }, name: "lsidTTLIndex", ns: "config.system.sessions", expireAfterSeconds: 1800 }
2019-08-07T19:31:13.603+0800 I INDEX [LogicalSessionCacheRefresh] building index using bulk method; build may temporarily use up to 500 megabytes of RAM
2019-08-07T19:31:13.611+0800 I INDEX [LogicalSessionCacheRefresh] build index done. scanned 0 total records. 0 secs

当出现2019-08-07T19:31:13.522+0800 I NETWORK [initandlisten] waiting for connections on port 27017 就代表启动成功了,并且可以在本地的27017端口访问到我们的数据库。

一些常用的mongodb命令

在终端mongo后就实现了本地与数据库的连接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
> use mylab
//表示移动到数据库mylab,如果没有则创建
> db
//查看当前数据库
> show dbs
//查看所有数据库
> db.dropDatabase()
//删除当前数据库
> show tables
//查看当前集合
> db.createCollection("lab")
//创建一个叫lab的集合
> db.collection.drop()
//删除当前集合

这些事创建数据库的方法,在终端上操作,对于数据库中数据的操作我们可以在mongoose中实现

mongoose

mongoose是可以让node.js操作mongodb的插件。

mongoose官方文档

安装

yarn add mongoose

1.定义架构

mongoose所有的内容都从Schema开头,相当于定义了一个模式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
var mongoose = require('mongoose');

var schema = mongoose.Schema({
name:{
type:String,
required:true
},
email:{
type:String,
required:true
},
password:{
type:String,
required:true
},
data:{
type:Data,
default:Date.now
},
access:{
type:String,
required:true
},
identity:{
type:String,
required:true
}
})

module.exports = mongoose.model('Users' , schema);

这是我定义的一个users的模版,首先引入mongoose,然后定义一个mongoose.Schema对象,其中定义了user的数据模型,比如有name是一个String,email也是一个string,然后required:true表示用来验证,这里我直接都给true,然后需要导出模块,导出时需要的是一个model对象,名字为Users,然后使用刚刚创建的Schema。

2.本地连接数据库

本地连接很简单,一个固定格式mongodb://localhost/dbname ,然后需要安装mongoose的依赖,然后在app.js中引入,连接数据库的函数mongoose.connect 我在使用的时候promise一下,在console会返回一个状态,如果失败则抛出异常:

1
2
3
4
5
6
var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/test' , { useNewUrlParser: true }
).then(()=>{
console.log("Database is connected");
}).catch(err => console.log(err));

3.使用数据模型

由于我们在导出了我们的数据模型模块Users,我们在使用数据模型时只需要引入即可

var User = require('../module/Users');

0%