-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongo.js
executable file
·36 lines (33 loc) · 1.23 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
const {MongoClient} = require('mongodb'),
cluster = require('cluster'),
co = require('./constants'),
w = require('./words'),
db = {};
(async () => {
for (let i in co.mongoClusters) {
if (co.mongoClusters[i].length === 1) {
db[i] = db[co.mongoClusters[i]];
continue;
}
const client = await MongoClient.connect(co.mongoClusters[i], {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 5000
}).catch(() => process.exit(0));
db[i] = await client.db(co.dbName);
if (cluster.isMaster) {
await checkIndex(db[i], w.users, w.email, i);
await checkIndex(db[i], w.deposits, w.data, i);
}
}
})();
async function checkIndex(db, collection, prop) {
const exist = await db.listCollections({name: collection}).toArray();
if (!exist.length) await db.createCollection(collection);
const indexes = await db.collection(collection).indexes();
if (!indexes.filter(({key}) => key[prop] !== undefined).length) {
await db.collection(collection).insertOne({[prop]: "test"});
await db.createIndex(collection, prop, {unique: true});
}
}
module.exports = db;