-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.js
59 lines (45 loc) · 1.46 KB
/
database.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
58
const {DB_NAME, DB_URL, COLL_NAME} = require('./config');
const _ = require('lodash');
const MongoClient = require('mongodb').MongoClient;
let client = new MongoClient(DB_URL);
let db;
let collection;
const connect = async () => {
try {
// OPEN CONNECTON
await client.connect();
console.log('[db] Connected to server');
db = client.db(DB_NAME);
collection = db.collection(COLL_NAME);
} catch (err) {
console.error(err);
}
}
// OUT [{'name': 'tz_id}, {}, {}]
const readUniqLocations = async () => {
try {
console.log('[db] Will read locations from mongo');
// fetch all data from 'current' coll, but only name and tz_id fields;
const locNamesZones = (await collection.find({}, {projection: {
"_id": 0,
"location.name": 1,
"location.tz_id": 1}
}).toArray())
.map(lno => lno['location']);
// await client.close();
// console.log('[db] Connected closed');
return _.uniqBy(locNamesZones, 'name');
// return [{name: aaa, tz_id: ...}, {}]
} catch (err) {
console.log('[db] Failed to read locations');
console.error(err);
}
}
const readAllbyLocation = async (name) => {
try {
return (await collection.find({'location.name':name}).toArray())
} catch (err) {
console.error(err);
}
}
module.exports = { connect, readUniqLocations, readAllbyLocation };