-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
49 lines (40 loc) · 1.14 KB
/
db.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
'use strict'
var _ = require('lodash')
var config = require('./config')
var mongo = require('monk')(`${config.MONGO_HOST}/${config.MONGO_MAIN_DB}`)
module.exports = mongo
function safeDrop (name) {
const p = mongo.get(name).drop()
return p.then(null, () => {
p.fulfill()
})
}
module.exports.clear = function () {
const collectionsToDrop = [].slice.call(arguments)
return Promise.all(collectionsToDrop.map(safeDrop))
}
module.exports.queryFields = function (fields) {
let mongoQuery = _.cloneDeep(module.exports.NO_MONGO_ID)
if (fields) {
for (let field of fields) {
mongoQuery.fields[field] = 1
}
}
return mongoQuery
}
module.exports.filterLink = function (name, id) {
return {[name]: id}
}
// cache to avoid expensive redundant calls to index same fields
var indexCache = {}
module.exports.ensureIndex = function (name, field) {
if (!indexCache[name]) {
indexCache[name] = new Set()
}
if (!indexCache[name].has(field)) {
indexCache[name].add(field)
mongo.get(name).ensureIndex({[field]: 'hashed'})
}
}
module.exports.NO_MONGO_ID = {fields: {_id: 0}}
module.exports.ID_ONLY = {fields: {id: 1, _id: 0}}