diff --git a/CHANGES_NEXT_RELEASE b/CHANGES_NEXT_RELEASE index 8b137891..8901e7e1 100644 --- a/CHANGES_NEXT_RELEASE +++ b/CHANGES_NEXT_RELEASE @@ -1 +1 @@ - +- Upgrade mongodb dep from 3.6.12 to 4.7.0 diff --git a/config.js b/config.js index ea8e1c39..06ab9e69 100644 --- a/config.js +++ b/config.js @@ -64,7 +64,9 @@ config.mongo = { // The URI to use for the database connection. It supports replica set URIs. // mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]] // I.e.: 'mongodb://user:pass@host1:27017,host2:27018,host3:27019/cep?replicaSet=myrep' - url: 'mongodb://localhost:27017/cep' + url: 'mongodb://localhost:27017/cep', + // MongoDB connection timeout. Default is 30000ms + connectTimeoutMS: 30000 }; /** diff --git a/docs/API/plain_rules.md b/docs/API/plain_rules.md index 87033e74..1803cae2 100644 --- a/docs/API/plain_rules.md +++ b/docs/API/plain_rules.md @@ -171,7 +171,8 @@ fields: - **checkInterval**: _mandatory_, time in minutes for checking the attribute. Min value is 0.5 and max is 35791, other values are truncated to them (a warning log message is generated if such truncation occurs) - **attribute**: _mandatory_, attribute for watch -- **reportInterval**: _mandatory_, time in seconds to see an entity as silent (in other words, how much time has to pass since last entity update to consider that entity is in "no signal" situation so the rule is triggered) +- **reportInterval**: _mandatory_, time in seconds to see an entity as silent (in other words, how much time has to + pass since last entity update to consider that entity is in "no signal" situation so the rule is triggered) - **id** or **idRegexp**: _mandatory_ (but not both at the same time), ID or regular expression of the entity to watch - type: _optional_, type of entities to watch @@ -181,10 +182,12 @@ checkInterval could impact on performance. ## Non signal actions The following virtual attributes are available to be used in non signal template actions: + - **service**: service of rule - **subservice**: subservice of rule - **ruleName**: name of the rule -- **reportInterval**: time to see an entity as silent (in other words, how much time has to pass since last entity update to consider that entity is in "no signal" situation so the rule is triggered) +- **reportInterval**: time to see an entity as silent (in other words, how much time has to pass since last entity + update to consider that entity is in "no signal" situation so the rule is triggered) - **id**: entity id - **type**: entity type - **internalCurrentTime**: current time @@ -1384,7 +1387,7 @@ will send to core the "event" "subservice": "/", "service": "unknownt", "myJsonValue__color": "blue", - "myJsonValue": {"type":"myType1","value":{"color":"blue"}}, + "myJsonValue": { "type": "myType1", "value": { "color": "blue" } }, "myArrayValue__0": "green", "myArrayValue__1": "black", "myArrayValue": { "type": "myType2", "value": ["green", "blue"] }, @@ -1412,7 +1415,7 @@ will send to core the "event" "location__lon": 53.120405283, "location__x": 642009.4673614734, "location__y": 5883931.8311913265, - "location": {"type":"Point","coordinates":[53.120405283,53.0859375]} + "location": { "type": "Point", "coordinates": [53.120405283, 53.0859375] } } ``` diff --git a/docs/roadmap.md b/docs/roadmap.md index b532a621..ecb51747 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -61,8 +61,7 @@ The following list contains all features that were in the roadmap and have alrea - Software quality improvement based on ISO25010 recommendations () ([1.12.0](https://github.com/telefonicaid/perseo-fe/releases/tag/1.12.0)) -- Nosignal actions supported in HA scenarios - () +- Nosignal actions supported in HA scenarios () ([1.12.0](https://github.com/telefonicaid/perseo-fe/releases/tag/1.12.0)) - Full support for pagination in APIs /rules and /vrules () ([1.10.0](https://github.com/telefonicaid/perseo-fe/releases/tag/1.10.0)) @@ -81,4 +80,3 @@ The following list contains all features that were in the roadmap and have alrea - Add astronomic clock support to timed rules (included sunrise and sunset functions for EPL statements) () ([Core 1.4.0](https://github.com/telefonicaid/perseo-core/releases/tag/1.4.0)) - diff --git a/lib/db.js b/lib/db.js index 6138a62a..4f571edc 100644 --- a/lib/db.js +++ b/lib/db.js @@ -51,10 +51,17 @@ function getDbAux(url, component, callback) { client.connect( url, { - bufferMaxEntries: config.checkDB.bufferMaxEntries, - domainsEnabled: true, - reconnectTries: config.checkDB.reconnectTries, - reconnectInterval: config.checkDB.reconnectInterval + // connectTimeoutMS is no longer supported in MongoDB 4.x + // (see https://stackoverflow.com/q/72699235/1485926) + // we keep connectTimeoutMS as configuration parameter, but + // the driver parameters are now socketTimeoutMS and + // serverSelectionTimeoutMS + socketTimeoutMS: config.mongo.connectTimeoutMS, + serverSelectionTimeoutMS: config.mongo.connectTimeoutMS + //bufferMaxEntries: config.checkDB.bufferMaxEntries, + //domainsEnabled: true, + //reconnectTries: config.checkDB.reconnectTries, + //reconnectInterval: config.checkDB.reconnectInterval //useUnifiedTopology: true }, function(err, client) { @@ -69,10 +76,10 @@ function getDbAux(url, component, callback) { // The driver has given up getting a connection, so we will die (restart perseo usually) // and re-try from scratch. // The ReplSet does not emit 'reconnectFailed' - db.serverConfig.on('reconnectFailed', function() { - logger.fatal('too many tries to reconnect to database, dying ...'); - process.exit(-2); - }); + //db.serverConfig.on('reconnectFailed', function() { + // logger.fatal('too many tries to reconnect to database, dying ...'); + // process.exit(-2); + //}); checkDbHealthFunc = function checkDbHealth() { pingAux(db, component, function(err, result) { @@ -98,21 +105,17 @@ function getOrionDb(callback) { } function ensureIndex(collection, fields, callback) { - database.collection(collection, function(err, collection) { - myutils.logErrorIf(err, collection, context); - collection.createIndex(fields, { unique: true }, function(err, indexName) { - myutils.logErrorIf(err, 'ensureIndex ' + collection, context); - callback(err, indexName); - }); + var col = database.collection(collection); + col.createIndex(fields, { unique: true }, function(err, indexName) { + myutils.logErrorIf(err, 'ensureIndex ' + collection, context); + callback(err, indexName); }); } function ensureIndexTTL(collection, fields, ttl, callback) { - database.collection(collection, function(err, collection) { - myutils.logErrorIf(err, collection); - collection.createIndex(fields, { expireAfterSeconds: ttl }, function(err, indexName) { - myutils.logErrorIf(err, 'ensureIndex ' + collection, context); - callback(err, indexName); - }); + var col = database.collection(collection); + col.createIndex(fields, { expireAfterSeconds: ttl }, function(err, indexName) { + myutils.logErrorIf(err, 'ensureIndex ' + collection, context); + callback(err, indexName); }); } diff --git a/lib/models/entitiesStore.js b/lib/models/entitiesStore.js index b279936d..871ca086 100644 --- a/lib/models/entitiesStore.js +++ b/lib/models/entitiesStore.js @@ -22,8 +22,7 @@ */ 'use strict'; -var async = require('async'), - appContext = require('../appContext'), +var appContext = require('../appContext'), config = require('../../config'), entitiesCollectionName = require('../../config').orionDb.collection, myutils = require('../myutils'), @@ -39,6 +38,11 @@ function findSilentEntities(service, subservice, ruleData, func, callback) { context = { op: 'checkNoSignal', comp: constants.COMPONENT_NAME }, criterion = {}; + var cb = function(err, result) { + logger.debug(context, 'findSilentEntities %s', myutils.firstChars(result)); + return callback(err, result); + }; + db = orionServiceDb(service); criterion['attrs.' + ruleData.attribute + '.modDate'] = { $lt: Date.now() / 1000 - ruleData.reportInterval @@ -60,32 +64,32 @@ function findSilentEntities(service, subservice, ruleData, func, callback) { criterion['_id.type'] = ruleData.type; } logger.debug(context, 'findSilentEntities criterion %j', criterion); - async.waterfall( - [ - db.collection.bind(db, entitiesCollectionName, { strict: true }), - function(col, cb) { - var count = 0; - col.find(criterion) - .batchSize(config.orionDb.batchSize) - .each(function(err, one) { - if (err) { - return cb(err, null); - } - if (one === null) { - //cursor exhausted - return cb(err, 'silent ones count ' + count); - } - logger.debug(context, 'silent entity %j', one._id); - func(one); - count++; - }); - } - ], - function(err, result) { - logger.debug(context, 'findSilentEntities %s', myutils.firstChars(result)); - return callback(err, result); + + myutils.collectionExists(db, entitiesCollectionName, function(exists) { + if (!exists) { + return cb('collection ' + entitiesCollectionName + ' does not exist'); } - ); + + var col = db.collection(entitiesCollectionName); + + var count = 0; + col.find(criterion) + .batchSize(config.orionDb.batchSize) + .forEach( + function(one) { + logger.debug(context, 'silent entity %j', one._id); + func(one); + count++; + }, + function(err) { + if (err) { + return cb(err, null); + } else { + return cb(null, 'silent ones count ' + count); + } + } + ); + }); } module.exports = { diff --git a/lib/models/executionsStore.js b/lib/models/executionsStore.js index 213345c0..a875b9fd 100644 --- a/lib/models/executionsStore.js +++ b/lib/models/executionsStore.js @@ -22,8 +22,7 @@ */ 'use strict'; -var async = require('async'), - appContext = require('../appContext'), +var appContext = require('../appContext'), logger = require('logops'), execCollectionName = require('../../config').collections.executions, myutils = require('../myutils'); @@ -37,11 +36,13 @@ module.exports = { id = task.event.id, index = task.action.index; - db.collection(execCollectionName, { strict: true }, function(err, col) { - if (err) { - myutils.logErrorIf(err); - return callback(err, null); + myutils.collectionExists(db, execCollectionName, function(exists) { + if (!exists) { + return callback('collection ' + execCollectionName + ' does not exist'); } + + const col = db.collection(execCollectionName); + var cursor = col .find( { @@ -66,18 +67,19 @@ module.exports = { }); }, AlreadyDone: function AlreadyDone(task, callback) { - var db = appContext.Db(), - service = task.event.service, - subservice = task.event.subservice, - ruleName = task.event.ruleName, - id = task.event.id, - index = task.action.index, - noticeId = task.event.noticeId; - db.collection(execCollectionName, { strict: true }, function(err, col) { - if (err) { - myutils.logErrorIf(err); - return callback(err, null); + myutils.collectionExists(appContext.Db(), execCollectionName, function(exists) { + if (!exists) { + return callback('collection ' + execCollectionName + ' does not exist'); } + + var col = appContext.Db().collection(execCollectionName), + service = task.event.service, + subservice = task.event.subservice, + ruleName = task.event.ruleName, + id = task.event.id, + index = task.action.index, + noticeId = task.event.noticeId; + col.findOne( { name: ruleName, @@ -98,37 +100,36 @@ module.exports = { }); }, Update: function Update(task, callback) { - var db = appContext.Db(), - service = task.event.service, - subservice = task.event.subservice, - ruleName = task.event.ruleName, - id = task.event.id, - index = task.action.index, - noticeId = task.event.noticeId; - async.waterfall( - [ - db.collection.bind(db, execCollectionName, { strict: true }), - function(col, cb) { - col.update( - { - name: ruleName, - subservice: subservice, - service: service, - id: id, - notice: noticeId, - index: index - }, - { $currentDate: { lastTime: true } }, - { upsert: true }, - cb - ); - } - ], - function(err, result) { - myutils.logErrorIf(err); - logger.info('executionsStore.Update %j', result); - return callback(err, result); + myutils.collectionExists(appContext.Db(), execCollectionName, function(exists) { + if (!exists) { + return callback('collection ' + execCollectionName + ' does not exist'); } - ); + + var col = appContext.Db().collection(execCollectionName), + service = task.event.service, + subservice = task.event.subservice, + ruleName = task.event.ruleName, + id = task.event.id, + index = task.action.index, + noticeId = task.event.noticeId; + + col.update( + { + name: ruleName, + subservice: subservice, + service: service, + id: id, + notice: noticeId, + index: index + }, + { $currentDate: { lastTime: true } }, + { upsert: true }, + function(err, result) { + myutils.logErrorIf(err); + logger.info('executionsStore.Update %j', result); + return callback(err, result); + } + ); + }); } }; diff --git a/lib/models/rulesStore.js b/lib/models/rulesStore.js index 8d01fd96..94988e20 100644 --- a/lib/models/rulesStore.js +++ b/lib/models/rulesStore.js @@ -23,12 +23,12 @@ 'use strict'; var util = require('util'), - async = require('async'), appContext = require('../appContext'), rulesCollectionName = require('../../config').collections.rules, myutils = require('../myutils'), logger = require('logops'), errors = {}; +const config = require('../../config'); function parsePostAxnParams(rule) { if (rule && rule.action && rule.action.type === 'post') { @@ -83,16 +83,13 @@ function stringifyPostAxnParams(rule) { } function search(rule, callback) { - var db = appContext.Db(); - async.waterfall( - [ - db.collection.bind(db, rulesCollectionName, { strict: true }), - function(col, cb) { - col.findOne({ name: rule.name, subservice: rule.subservice, service: rule.service }, cb); - } - ], - callback - ); + myutils.collectionExists(appContext.Db(), rulesCollectionName, function(exists) { + if (!exists) { + return callback('collection ' + rulesCollectionName + ' does not exist'); + } + var col = appContext.Db().collection(rulesCollectionName); + col.findOne({ name: rule.name, subservice: rule.subservice, service: rule.service }, callback); + }); } function findAll(service, subservice, callback) { @@ -105,26 +102,25 @@ function findAll(service, subservice, callback) { criterion.subservice = subservice; } var db = appContext.Db(); - async.waterfall( - [ - db.collection.bind(db, rulesCollectionName, { strict: true }), - function(col, cb) { - col.find(criterion).toArray(function(err, rules) { - if (rules && util.isArray(rules)) { - rules.forEach(function(r) { - parsePostAxnParams(r); - }); - } - cb(err, rules); + myutils.collectionExists(db, rulesCollectionName, function(exists) { + if (!exists) { + return callback('collection ' + rulesCollectionName + ' does not exist'); + } + + const col = db.collection(rulesCollectionName); + + col.find(criterion).toArray(function(err, rules) { + if (rules && util.isArray(rules)) { + rules.forEach(function(r) { + parsePostAxnParams(r); }); } - ], - function(err, result) { + myutils.logErrorIf(err); - logger.info('rulesStore.FindAll %s', myutils.firstChars(result)); - return callback(err, result); - } - ); + logger.info('rulesStore.FindAll %s', myutils.firstChars(rules)); + return callback(err, rules); + }); + }); } module.exports = { @@ -150,69 +146,72 @@ module.exports = { }, FindAll: findAll, Remove: function Remove(rule, callback) { - var db = appContext.Db(); - async.waterfall( - [ - db.collection.bind(db, rulesCollectionName, { strict: true }), - function(col, cb) { - col.remove({ name: rule.name, subservice: rule.subservice, service: rule.service }, cb); - } - ], - function(err, result) { + myutils.collectionExists(appContext.Db(), rulesCollectionName, function(exists) { + if (!exists) { + return callback('collection ' + rulesCollectionName + ' does not exist'); + } + + var col = appContext.Db().collection(rulesCollectionName); + col.remove({ name: rule.name, subservice: rule.subservice, service: rule.service }, function(err, result) { myutils.logErrorIf(err); logger.info('rulesStore.Remove %j', myutils.firstChars(result)); return callback(err, result); - } - ); + }); + }); }, Save: function Save(r, callback) { - var db = appContext.Db(); - stringifyPostAxnParams(r); - async.waterfall( - [ - db.collection.bind(db, rulesCollectionName, { strict: true }), - function(col, cb) { - col.save(r, cb); - } - ], - function(err, result) { - myutils.logErrorIf(err); - logger.info('rulesStore.Save %j', myutils.firstChars(result)); - return callback(err, result); + var cb = function(err, result) { + myutils.logErrorIf(err); + logger.info('rulesStore.Save %j', myutils.firstChars(result)); + return callback(err, result); + }; + + myutils.collectionExists(appContext.Db(), rulesCollectionName, function(exists) { + if (!exists) { + return cb('collection ' + config.collections.rules + ' does not exist'); } - ); + + var col = appContext.Db().collection(rulesCollectionName); + stringifyPostAxnParams(r); + // Depending if r has _id or not we use updateOne or insertOne + if (r._id) { + col.updateOne({ _id: r._id }, r, cb); + } else { + col.insertOne(r, cb); + } + }); }, Update: function Update(id, r, callback) { - var db = appContext.Db(); - stringifyPostAxnParams(r); - async.waterfall( - [ - db.collection.bind(db, rulesCollectionName, { strict: true }), - function(col, cb) { - col.findOneAndUpdate( - { name: id }, - { $set: r }, - { - upsert: false, - returnNewDocument: true - }, - function(err, result) { - if (result && result.lastErrorObject && result.lastErrorObject.updatedExisting === false) { - return cb(new errors.NotFoundRule(id), null); - } - parsePostAxnParams(r); - logger.debug('rulesStore.findOneAndUpdate %s', myutils.firstChars(r)); - return cb(err, r); - } - ); - } - ], - function(err, result) { - myutils.logErrorIf(err); - logger.info('rulesStore.Update %j', myutils.firstChars(result)); - return callback(err, result); + var cb = function(err, result) { + myutils.logErrorIf(err); + logger.info('rulesStore.Update %j', myutils.firstChars(result)); + return callback(err, result); + }; + + myutils.collectionExists(appContext.Db(), rulesCollectionName, function(exists) { + if (!exists) { + return cb('collection ' + config.collections.rules + ' does not exist'); } - ); + var col = appContext.Db().collection(rulesCollectionName); + stringifyPostAxnParams(r); + + col.findOneAndUpdate( + { name: id }, + { $set: r }, + { + upsert: false, + returnNewDocument: true + }, + function(err, result) { + if (result && result.lastErrorObject && result.lastErrorObject.updatedExisting === false) { + return cb(new errors.NotFoundRule(id), null); + } + parsePostAxnParams(r); + logger.debug('rulesStore.findOneAndUpdate %s', myutils.firstChars(r)); + return cb(err, r); + } + ); + }); } }; /** diff --git a/lib/models/updateAction.js b/lib/models/updateAction.js index dddd61c6..6a0efa3a 100644 --- a/lib/models/updateAction.js +++ b/lib/models/updateAction.js @@ -486,8 +486,12 @@ function doUpdateActionWithFilter(queryOptions, action, event, token, connection // If the error was reported by Orion, error.correlator will be // filled with the associated transaction id metrics.IncMetrics(event.service, event.subservice, metrics.failedActionEntityUpdate); - logger.warn('error v2.batchUpdate: %j trying update entity %j after event %j', - error, changes, event); + logger.warn( + 'error v2.batchUpdate: %j trying update entity %j after event %j', + error, + changes, + event + ); alarm.raise(alarm.ORION, null, error); } ); // batchUpdate @@ -538,8 +542,7 @@ function doUpdateAction(action, event, token, connection, callback) { }, (error) => { metrics.IncMetrics(event.service, event.subservice, metrics.failedActionEntityUpdate); - logger.warn('error v2.batchUpdate: %j trying update entity %j after event %j', - error, changes, event); + logger.warn('error v2.batchUpdate: %j trying update entity %j after event %j', error, changes, event); alarm.raise(alarm.ORION, null, error); callback(error, null); } diff --git a/lib/myutils.js b/lib/myutils.js index 2d1915f0..328d47a3 100644 --- a/lib/myutils.js +++ b/lib/myutils.js @@ -402,6 +402,20 @@ function purgeRuleAuthPassword(rule) { return rule; } +function collectionExists(db, colName, callback) { + var found = false; + db.listCollections({}, { nameOnly: true }).forEach( + function(col) { + if (col.name === colName) { + found = true; + } + }, + function() { + callback(found); + } + ); +} + /** * expandVar substitutes every variable in val (denoted as $(var}) with the value * in mappings (as dictionary), getting the key 'var' from the object @@ -512,3 +526,14 @@ module.exports.ruleWithContextTimedRule = ruleWithContextTimedRule; * @param {Object} Object rule */ module.exports.purgeRuleAuthPassword = purgeRuleAuthPassword; + +/** + * collectionExists checks if a given collection exists (to get in mongodb 4.x the same "strict mode" + * we had in mongodb 3.x, this way achieving full backward compatibility). Check also + * https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/CHANGES_4.0.0.md#dbcollection-no-longer-accepts-a-callback + * + * @param {object} db + * @param {string} colName + * @param {function} callback function(found) + */ +module.exports.collectionExists = collectionExists; diff --git a/package.json b/package.json index 3f146857..4cc29c48 100644 --- a/package.json +++ b/package.json @@ -62,7 +62,7 @@ "body-parser": "~1.18.2", "express": "4.18.1", "logops": "2.1.2", - "mongodb": "3.6.12", + "mongodb": "4.7.0", "ngsijs": "1.4.1", "nodemailer": "6.6.5", "nodemailer-smtp-transport": "~2.7.2", diff --git a/test/component/db_test.js b/test/component/db_test.js index 29c02d86..c2aca532 100644 --- a/test/component/db_test.js +++ b/test/component/db_test.js @@ -30,12 +30,16 @@ var should = require('should'), describe('Db', function() { describe('#GetDB()', function() { var mongourl = ''; + var connectTimeoutMS; before(function() { mongourl = utilsT.getConfig().mongo.url; + connectTimeoutMS = utilsT.getConfig().mongo.connectTimeoutMS; utilsT.getConfig().mongo.url = 'mongodb://ihopethisdoesnotexistpleeease:32321/perseo_testing'; + utilsT.getConfig().mongo.connectTimeoutMS = 200; }); after(function() { utilsT.getConfig().mongo.url = mongourl; + utilsT.getConfig().mongo.connectTimeoutMS = connectTimeoutMS; }); it('should return an error when there is no database', function(done) { db.getDb(function(error, database) { diff --git a/test/utils/utilsT.js b/test/utils/utilsT.js index eb868217..984c78f9 100644 --- a/test/utils/utilsT.js +++ b/test/utils/utilsT.js @@ -56,18 +56,14 @@ function remove(collection, callback) { if (err) { return callback(err); } - const db = client.db(); - db.collection(collection, {}, function(err, coll) { + const coll = client.db().collection(collection); + + coll.remove({}, function(err, result) { if (err) { return callback(err); } - coll.remove({}, function(err, result) { - if (err) { - return callback(err); - } - client.close(); - return callback(null, result); - }); + client.close(); + return callback(null, result); }); } ); @@ -87,18 +83,13 @@ function dropCollection(collection, callback) { if (err) { return callback(err); } - const db = client.db(); - db.collection(collection, {}, function(err, col) { + const col = client.db().collection(collection); + col.drop(function(err, result) { if (err) { return callback(err); } - col.drop(function(err, result) { - if (err) { - return callback(err); - } - client.close(); - return callback(null, result); - }); + client.close(); + return callback(null, result); }); } ); @@ -117,15 +108,11 @@ function createRulesCollection(callback) { if (err) { return callback(err); } - const db = client.db(); - db.collection(config.collections.rules, {}, function(err, rules) { - if (err) { - return callback(err); - } - rules.ensureIndex({ name: 1 }, { unique: true, w: 'majority' }, function(err, indexName) { - client.close(); - return callback(err, indexName); - }); + const rules = client.db().collection(config.collections.rules); + + rules.createIndex({ name: 1 }, { unique: true, w: 'majority' }, function(err, indexName) { + client.close(); + return callback(err, indexName); }); } ); @@ -138,18 +125,14 @@ function addRule(rule, callback) { if (err) { return callback(err); } - const db = client.db(); - db.collection(config.collections.rules, {}, function(err, rules) { + const rules = client.db().collection(config.collections.rules); + + rules.insertOne(rule, function(err, result) { if (err) { return callback(err); } - rules.save(rule, function(err, result) { - if (err) { - return callback(err); - } - client.close(); - return callback(null, result); - }); + client.close(); + return callback(null, result); }); } ); @@ -163,15 +146,12 @@ function createEntitiesCollection(tenant, callback) { if (err) { return callback(err); } - db2.collection(config.orionDb.collection, {}, function(err, rules) { - if (err) { - return callback(err); - } - // We don't mind what fields have index in that collection - rules.ensureIndex({ modDate: 1 }, { unique: true, w: 'majority' }, function(err, indexName) { - client.close(); - return callback(err, indexName); - }); + var rules = db2.collection(config.orionDb.collection); + + // We don't mind what fields have index in that collection + rules.createIndex({ modDate: 1 }, { unique: true, w: 'majority' }, function(err, indexName) { + client.close(); + return callback(err, indexName); }); } ); @@ -180,21 +160,18 @@ function dropEntities(callback) { MongoClient.connect( config.orionDb.url, function(err, client) { - var db2 = client.db(config.orionDb.prefix + '-' + config.DEFAULT_TENANT); + var db2 = client.db(config.orionDb.prefix + '-' + config.DEFAULT_SERVICE); if (err) { return callback(err); } - db2.collection(config.orionDb.collection, {}, function(err, coll) { + var coll = db2.collection(config.orionDb.collection); + + coll.remove({}, function(err, result) { if (err) { return callback(err); } - coll.remove({}, function(err, result) { - if (err) { - return callback(err); - } - client.close(); - return callback(null, result); - }); + client.close(); + return callback(null, result); }); } ); @@ -208,17 +185,14 @@ function addEntity(tenant, entity, callback) { return callback(err); } db2 = client.db(config.orionDb.prefix + '-' + tenant); - db2.collection(config.orionDb.collection, {}, function(err, entities) { + var entities = db2.collection(config.orionDb.collection); + + entities.insertOne(entity, function(err, result) { if (err) { return callback(err); } - entities.save(entity, function(err, result) { - if (err) { - return callback(err); - } - client.close(); - return callback(null, result); - }); + client.close(); + return callback(null, result); }); } );