-
Notifications
You must be signed in to change notification settings - Fork 6
/
mongo.js
57 lines (48 loc) · 1.33 KB
/
mongo.js
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
'use strict';
const { MongoClient } = require('mongodb');
// 获取数据库相关的静态数据
const config = require('./config');
let _db = null;
/**
* 连接到数据库,并将连接保存到 _db 中
*
* @returns {Promise<MongoClient>} 生成 mongoClient 的 promise
*/
let mongoConnect = async () => {
try {
let { host, port, username, password, databaseName } = config.mongo;
let linkUrl = `mongodb://${host}:${port}/`;
/* istanbul ignore next */
if (username && password) {
linkUrl = `mongodb://${username}:${password}@${host}:${port}/${databaseName}`;
}
_db = (await MongoClient.connect(linkUrl, { useNewUrlParser: true, useUnifiedTopology: true })).db(databaseName);
// 绑定快捷路径
exports.User = _db.collection('user');
exports.Save = _db.collection('save');
exports.WhiteList = _db.collection('whiteList');
return _db;
} catch (err) {
/* istanbul ignore next */
console.error(err);
/* istanbul ignore next */
process.exit(10);
}
};
let connection = mongoConnect();
/**
* 一个 Promise
* 数据库连接完成后会被 resolve
*
* @returns {Promise<Null>} 无意义
*/
let prepare = async () => {
/* istanbul ignore else */
if (!_db) await connection;
};
exports = module.exports = {
get client() {
return _db;
},
prepare: prepare,
};