diff --git a/benchmarks/index.js b/benchmarks/index.js index 784e6dbf3..e4a7fd6c6 100644 --- a/benchmarks/index.js +++ b/benchmarks/index.js @@ -5,29 +5,29 @@ 'use strict'; -var DataSource = require('loopback-datasource-juggler').DataSource; -var connector = require('..'); -var Benchmark = require('benchmark'); +const DataSource = require('loopback-datasource-juggler').DataSource; +const connector = require('..'); +const Benchmark = require('benchmark'); -var ds = new DataSource(connector, { +const ds = new DataSource(connector, { host: process.env.LB_HOST || '127.0.0.1', port: process.env.LB_PORT || 27017, database: process.env.LB_DB || 'strongloop', }); -var Todo = ds.define('Todo', { +const Todo = ds.define('Todo', { content: {type: String}, }); // not critical for MongoDB, but may uncover inefficiencies in SQL connectors // https://github.com/strongloop/loopback-connector-mongodb/pull/124/files#r28435614 -var uniqVal = 0; +let uniqVal = 0; function resetTestState() { uniqVal = 0; Todo.destroyAll(); } -var suite = new Benchmark.Suite(); +const suite = new Benchmark.Suite(); suite .on('start', function() { console.log('#', new Date()); diff --git a/example/model.js b/example/model.js index cf0fee007..9f0da980e 100644 --- a/example/model.js +++ b/example/model.js @@ -5,15 +5,15 @@ 'use strict'; -var g = require('strong-globalize')(); +const g = require('strong-globalize')(); -var DataSource = require('loopback-datasource-juggler').DataSource; +const DataSource = require('loopback-datasource-juggler').DataSource; -var config = require('rc')('loopback', {dev: {mongodb: {}}}).dev.mongodb; +const config = require('rc')('loopback', {dev: {mongodb: {}}}).dev.mongodb; -var ds = new DataSource(require('../'), config); +const ds = new DataSource(require('../'), config); -var Customer = ds.createModel('customer', { +const Customer = ds.createModel('customer', { seq: {type: Number, id: true}, name: String, emails: [{label: String, email: String}], diff --git a/index.js b/index.js index 54f52c8fd..b6ce0ae82 100644 --- a/index.js +++ b/index.js @@ -5,7 +5,7 @@ 'use strict'; -var SG = require('strong-globalize'); +const SG = require('strong-globalize'); SG.SetRootDir(__dirname); module.exports = require('./lib/mongodb'); diff --git a/leak-detection/fixtures/todo.js b/leak-detection/fixtures/todo.js index c84bc6aad..dabd9f8fc 100644 --- a/leak-detection/fixtures/todo.js +++ b/leak-detection/fixtures/todo.js @@ -5,15 +5,15 @@ 'use strict'; -var DataSource = require('loopback-datasource-juggler').DataSource; -var connector = require('../..'); +const DataSource = require('loopback-datasource-juggler').DataSource; +const connector = require('../..'); -var db = new DataSource(connector, { +const db = new DataSource(connector, { host: process.env.LB_HOST || '127.0.0.1', port: process.env.LB_PORT || 27017, database: process.env.LB_DB || 'strongloop', }); -var Todo = db.define('Todo', { +const Todo = db.define('Todo', { content: {type: String}, }); diff --git a/leak-detection/leak-detector.test.js b/leak-detection/leak-detector.test.js index e0bda911d..9c0e5e701 100644 --- a/leak-detection/leak-detector.test.js +++ b/leak-detection/leak-detector.test.js @@ -5,14 +5,14 @@ 'use strict'; -var memwatch; +let memwatch; try { memwatch = require('@airbnb/node-memwatch'); } catch (e) { memwatch = require('memwatch-next'); } -var sinon = require('sinon'); +const sinon = require('sinon'); describe('leak detector', function() { before(function() { @@ -21,18 +21,18 @@ describe('leak detector', function() { }); it('should detect a basic leak', function(done) { - var test = this; - var iterations = 0; - var leaks = []; - var interval = setInterval(function() { + const test = this; + const iterations = 0; + const leaks = []; + const interval = setInterval(function() { if (test.iterations >= global.ITERATIONS || test.spy.called) { test.spy.called.should.be.True(); clearInterval(interval); return done(); } test.iterations++; - for (var i = 0; i < 1000000; i++) { - var str = 'leaky string'; + for (let i = 0; i < 1000000; i++) { + const str = 'leaky string'; leaks.push(str); } }, 0); diff --git a/leak-detection/mongodb.test.js b/leak-detection/mongodb.test.js index 7f6dd0bba..c15974af7 100644 --- a/leak-detection/mongodb.test.js +++ b/leak-detection/mongodb.test.js @@ -5,9 +5,9 @@ 'use strict'; -var memwatch = require('memwatch-next'); -var sinon = require('sinon'); -var Todo = require('./fixtures/todo'); +const memwatch = require('memwatch-next'); +const sinon = require('sinon'); +const Todo = require('./fixtures/todo'); describe('mongodb', function() { before(function() { @@ -26,12 +26,12 @@ describe('mongodb', function() { } function execute(ctx, func, options, done) { - var hasOptions = true; + let hasOptions = true; if (typeof options === 'function') { done = options; hasOptions = false; } - var interval = setInterval(function() { + const interval = setInterval(function() { if (ctx.iterations >= global.ITERATIONS || ctx.spy.called) { ctx.spy.called.should.be.False(); clearInterval(interval); diff --git a/lib/mongodb.js b/lib/mongodb.js index 7b1fe4598..918b9cfd1 100644 --- a/lib/mongodb.js +++ b/lib/mongodb.js @@ -8,15 +8,15 @@ /*! * Module dependencies */ -var bson = require('bson'); -var g = require('strong-globalize')(); -var mongodb = require('mongodb'); -var urlParser = require('mongodb/lib/url_parser'); -var util = require('util'); -var async = require('async'); -var Connector = require('loopback-connector').Connector; -var debug = require('debug')('loopback:connector:mongodb'); -var Decimal128 = mongodb.Decimal128; +const bson = require('bson'); +const g = require('strong-globalize')(); +const mongodb = require('mongodb'); +const urlParser = require('mongodb/lib/url_parser'); +const util = require('util'); +const async = require('async'); +const Connector = require('loopback-connector').Connector; +const debug = require('debug')('loopback:connector:mongodb'); +const Decimal128 = mongodb.Decimal128; exports.ObjectID = ObjectID; /*! @@ -56,8 +56,8 @@ function generateMongoDBURL(options) { options.hostname = options.hostname || options.host || '127.0.0.1'; options.port = options.port || 27017; options.database = options.database || options.db || 'test'; - var username = options.username || options.user; - var portUrl = ''; + const username = options.username || options.user; + let portUrl = ''; // only include port if not using mongodb+srv if (options.protocol !== 'mongodb+srv') { portUrl = ':' + options.port; @@ -97,7 +97,7 @@ exports.initialize = function initializeDataSource(dataSource, callback) { return; } - var s = dataSource.settings; + const s = dataSource.settings; s.safe = s.safe !== false; s.w = s.w || 1; @@ -206,7 +206,7 @@ util.inherits(MongoDB, Connector); * @param {Db} db The mongo DB object */ MongoDB.prototype.connect = function(callback) { - var self = this; + const self = this; if (self.db) { process.nextTick(function() { if (callback) callback(null, self.db); @@ -219,7 +219,7 @@ MongoDB.prototype.connect = function(callback) { }); } else { // See https://github.com/mongodb/node-mongodb-native/blob/3.0.0/lib/mongo_client.js#L37 - var validOptionNames = [ + const validOptionNames = [ 'poolSize', 'ssl', 'sslValidate', @@ -287,8 +287,8 @@ MongoDB.prototype.connect = function(callback) { 'db', ]; - var lbOptions = Object.keys(self.settings); - var validOptions = {}; + const lbOptions = Object.keys(self.settings); + const validOptions = {}; lbOptions.forEach(function(option) { if (validOptionNames.indexOf(option) > -1) { validOptions[option] = self.settings[option]; @@ -340,7 +340,7 @@ MongoDB.prototype.getDefaultIdType = function() { * @returns {String} collection name */ MongoDB.prototype.collectionName = function(modelName) { - var modelClass = this._models[modelName]; + const modelClass = this._models[modelName]; if (modelClass.settings.mongodb) { modelName = modelClass.settings.mongodb.collection || modelName; } @@ -356,7 +356,7 @@ MongoDB.prototype.collection = function(modelName) { if (!this.db) { throw new Error(g.f('{{MongoDB}} connection is not established')); } - var collectionName = this.collectionName(modelName); + const collectionName = this.collectionName(modelName); return this.db.collection(collectionName); }; @@ -370,10 +370,10 @@ MongoDB.prototype.fromDatabase = function(modelName, data) { if (!data) { return null; } - var modelInfo = this._models[modelName] || this.dataSource.modelBuilder.definitions[modelName]; - var props = modelInfo.properties; - for (var p in props) { - var prop = props[p]; + const modelInfo = this._models[modelName] || this.dataSource.modelBuilder.definitions[modelName]; + const props = modelInfo.properties; + for (const p in props) { + const prop = props[p]; if (prop && prop.type === Buffer) { if (data[p] instanceof mongodb.Binary) { // Convert the Binary into Buffer @@ -413,7 +413,7 @@ MongoDB.prototype.fromDatabase = function(modelName, data) { */ MongoDB.prototype.toDatabase = function(modelName, data) { const modelInstance = this._models[modelName].model; - var props = this._models[modelName].properties; + const props = this._models[modelName].properties; if (this.settings.enableGeoIndexing !== true) { visitAllProperties(data, modelInstance, coerceDecimalProperty); @@ -422,8 +422,8 @@ MongoDB.prototype.toDatabase = function(modelName, data) { return data; } - for (var p in props) { - var prop = props[p]; + for (const p in props) { + const prop = props[p]; const isGeoPoint = data[p] && prop && prop.type && prop.type.name === 'GeoPoint'; if (isGeoPoint) { data[p] = { @@ -447,11 +447,11 @@ MongoDB.prototype.toDatabase = function(modelName, data) { * @param [...] params Parameters for the given command */ MongoDB.prototype.execute = function(modelName, command) { - var self = this; + const self = this; // Get the parameters for the given command - var args = [].slice.call(arguments, 2); + const args = [].slice.call(arguments, 2); // The last argument must be a callback function - var callback = args[args.length - 1]; + const callback = args[args.length - 1]; // Topology is destroyed when the server is disconnected // Execute if DB is connected and functional otherwise connect/reconnect first @@ -476,8 +476,8 @@ MongoDB.prototype.execute = function(modelName, command) { } function doExecute() { - var collection; - var context = Object.assign({}, { + let collection; + const context = Object.assign({}, { model: modelName, collection: collection, req: { @@ -522,12 +522,12 @@ MongoDB.prototype.execute = function(modelName, command) { MongoDB.prototype.coerceId = function(modelName, id, options) { // See https://github.com/strongloop/loopback-connector-mongodb/issues/206 if (id == null) return id; - var self = this; - var idValue = id; - var idName = self.idName(modelName); + const self = this; + let idValue = id; + const idName = self.idName(modelName); // Type conversion for id - var idProp = self.getPropertyDefinition(modelName, idName); + const idProp = self.getPropertyDefinition(modelName, idName); if (idProp && typeof idProp.type === 'function') { if (!(idValue instanceof idProp.type)) { idValue = idProp.type(id); @@ -551,17 +551,17 @@ MongoDB.prototype.coerceId = function(modelName, id, options) { * @param {Function} [callback] The callback function */ MongoDB.prototype.create = function(modelName, data, options, callback) { - var self = this; + const self = this; if (self.debug) { debug('create', modelName, data); } - var idValue = self.getIdValue(modelName, data); - var idName = self.idName(modelName); + let idValue = self.getIdValue(modelName, data); + const idName = self.idName(modelName); if (idValue === null) { delete data[idName]; // Allow MongoDB to generate the id } else { - var oid = self.coerceId(modelName, idValue, options); // Is it an Object ID?c + const oid = self.coerceId(modelName, idValue, options); // Is it an Object ID?c data._id = oid; // Set it to _id if (idName !== '_id') { delete data[idName]; @@ -597,14 +597,14 @@ MongoDB.prototype.create = function(modelName, data, options, callback) { * @param {Function} [callback] The callback function */ MongoDB.prototype.save = function(modelName, data, options, callback) { - var self = this; + const self = this; if (self.debug) { debug('save', modelName, data); } - var idValue = self.getIdValue(modelName, data); - var idName = self.idName(modelName); + const idValue = self.getIdValue(modelName, data); + const idName = self.idName(modelName); - var oid = self.coerceId(modelName, idValue, options); + const oid = self.coerceId(modelName, idValue, options); data._id = oid; if (idName !== '_id') { delete data[idName]; @@ -623,7 +623,7 @@ MongoDB.prototype.save = function(modelName, data, options, callback) { debug('save.callback', modelName, err, result); } - var info = {}; + const info = {}; if (result && result.result) { // create result formats: // { ok: 1, n: 1, upserted: [ [Object] ] } @@ -653,7 +653,7 @@ MongoDB.prototype.save = function(modelName, data, options, callback) { * */ MongoDB.prototype.exists = function(modelName, id, options, callback) { - var self = this; + const self = this; if (self.debug) { debug('exists', modelName, id); } @@ -673,12 +673,12 @@ MongoDB.prototype.exists = function(modelName, id, options, callback) { * @param {Function} [callback] The callback function */ MongoDB.prototype.find = function find(modelName, id, options, callback) { - var self = this; + const self = this; if (self.debug) { debug('find', modelName, id); } - var idName = self.idName(modelName); - var oid = self.coerceId(modelName, id, options); + const idName = self.idName(modelName); + const oid = self.coerceId(modelName, id, options); this.execute(modelName, 'findOne', {_id: oid}, function(err, data) { if (self.debug) { debug('find.callback', modelName, id, err, data); @@ -705,11 +705,11 @@ Connector.defineAliases(MongoDB.prototype, 'find', 'findById'); */ MongoDB.prototype.parseUpdateData = function(modelName, data, options) { options = options || {}; - var parsedData = {}; + const parsedData = {}; - var modelClass = this._models[modelName]; + const modelClass = this._models[modelName]; - var allowExtendedOperators = this.settings.allowExtendedOperators; + let allowExtendedOperators = this.settings.allowExtendedOperators; if (options.hasOwnProperty('allowExtendedOperators')) { allowExtendedOperators = options.allowExtendedOperators === true; } else if ( @@ -725,7 +725,7 @@ MongoDB.prototype.parseUpdateData = function(modelName, data, options) { if (allowExtendedOperators) { // Check for other operators and sanitize the data obj - var acceptedOperators = [ + const acceptedOperators = [ // Field operators '$currentDate', '$inc', @@ -747,10 +747,10 @@ MongoDB.prototype.parseUpdateData = function(modelName, data, options) { '$bit', ]; - var usedOperators = 0; + let usedOperators = 0; // each accepted operator will take its place on parsedData if defined - for (var i = 0; i < acceptedOperators.length; i++) { + for (let i = 0; i < acceptedOperators.length; i++) { if (data[acceptedOperators[i]]) { parsedData[acceptedOperators[i]] = data[acceptedOperators[i]]; usedOperators++; @@ -781,14 +781,14 @@ MongoDB.prototype.updateOrCreate = function updateOrCreate( options, callback ) { - var self = this; + const self = this; if (self.debug) { debug('updateOrCreate', modelName, data); } - var id = self.getIdValue(modelName, data); - var idName = self.idName(modelName); - var oid = self.coerceId(modelName, id, options); + const id = self.getIdValue(modelName, data); + const idName = self.idName(modelName); + const oid = self.coerceId(modelName, id, options); delete data[idName]; data = self.toDatabase(modelName, data); @@ -812,7 +812,7 @@ MongoDB.prototype.updateOrCreate = function updateOrCreate( if (self.debug) { debug('updateOrCreate.callback', modelName, id, err, result); } - var object = result && result.value; + const object = result && result.value; if (!err && !object) { // No result err = 'No ' + modelName + ' found for id ' + id; @@ -824,7 +824,7 @@ MongoDB.prototype.updateOrCreate = function updateOrCreate( } } - var info; + let info; if (result && result.lastErrorObject) { info = {isNewInstance: !result.lastErrorObject.updatedExisting}; } else { @@ -849,9 +849,9 @@ MongoDB.prototype.updateOrCreate = function updateOrCreate( MongoDB.prototype.replaceOrCreate = function(modelName, data, options, cb) { if (this.debug) debug('replaceOrCreate', modelName, data); - var id = this.getIdValue(modelName, data); - var oid = this.coerceId(modelName, id, options); - var idName = this.idName(modelName); + const id = this.getIdValue(modelName, data); + const oid = this.coerceId(modelName, id, options); + const idName = this.idName(modelName); data._id = data[idName]; delete data[idName]; this.replaceWithOptions(modelName, oid, data, {upsert: true}, cb); @@ -864,7 +864,7 @@ MongoDB.prototype.replaceOrCreate = function(modelName, data, options, cb) { * @param [callback] The callback function */ MongoDB.prototype.destroy = function destroy(modelName, id, options, callback) { - var self = this; + const self = this; if (self.debug) { debug('delete', modelName, id); } @@ -873,7 +873,7 @@ MongoDB.prototype.destroy = function destroy(modelName, id, options, callback) { if (self.debug) { debug('delete.callback', modelName, id, err, result); } - var res = result && result.result; + let res = result && result.result; if (res) { res = {count: res.n}; } @@ -904,24 +904,24 @@ function idIncluded(fields, idName) { // Excluded return false; } - for (var f in fields) { + for (const f in fields) { return !fields[f]; // If the fields has exclusion } return true; } MongoDB.prototype.buildWhere = function(modelName, where, options) { - var self = this; - var query = {}; + const self = this; + const query = {}; if (where === null || typeof where !== 'object') { return query; } where = sanitizeFilter(where, options); - var idName = self.idName(modelName); + const idName = self.idName(modelName); Object.keys(where).forEach(function(k) { - var cond = where[k]; + let cond = where[k]; if (k === 'and' || k === 'or' || k === 'nor') { if (Array.isArray(cond)) { cond = cond.map(function(c) { @@ -935,12 +935,12 @@ MongoDB.prototype.buildWhere = function(modelName, where, options) { if (k === idName) { k = '_id'; } - var propName = k; + let propName = k; if (k === '_id') { propName = idName; } - var prop = self.getPropertyDefinition(modelName, propName); + const prop = self.getPropertyDefinition(modelName, propName); const isDecimal = prop && prop.mongodb && prop.mongodb.dataType && @@ -953,8 +953,8 @@ MongoDB.prototype.buildWhere = function(modelName, where, options) { // Convert property to database column name k = self.getDatabaseColumnName(modelName, k); - var spec = false; - var regexOptions = null; + let spec = false; + let regexOptions = null; if (cond && cond.constructor.name === 'Object') { regexOptions = cond.options; spec = Object.keys(cond)[0]; @@ -1021,12 +1021,12 @@ MongoDB.prototype.buildWhere = function(modelName, where, options) { }; MongoDB.prototype.buildSort = function(modelName, order, options) { - var sort = {}; - var idName = this.idName(modelName); + let sort = {}; + const idName = this.idName(modelName); - var modelClass = this._models[modelName]; + const modelClass = this._models[modelName]; - var disableDefaultSort = false; + let disableDefaultSort = false; if (this.settings.hasOwnProperty('disableDefaultSort')) { disableDefaultSort = this.settings.disableDefaultSort; } @@ -1038,20 +1038,20 @@ MongoDB.prototype.buildSort = function(modelName, order, options) { } if (!order && !disableDefaultSort) { - var idNames = this.idNames(modelName); + const idNames = this.idNames(modelName); if (idNames && idNames.length) { order = idNames; } } if (order) { order = sanitizeFilter(order, options); - var keys = order; + let keys = order; if (typeof keys === 'string') { keys = keys.split(','); } - for (var index = 0, len = keys.length; index < len; index++) { - var m = keys[index].match(/\s+(A|DE)SC$/); - var key = keys[index]; + for (let index = 0, len = keys.length; index < len; index++) { + const m = keys[index].match(/\s+(A|DE)SC$/); + let key = keys[index]; key = key.replace(/\s+(A|DE)SC$/, '').trim(); if (key === idName) { key = '_id'; @@ -1098,10 +1098,10 @@ function buildNearFilter(query, params) { } params.forEach(function(near) { - var coordinates = {}; + let coordinates = {}; if (typeof near.near === 'string') { - var s = near.near.split(','); + const s = near.near.split(','); coordinates.lng = parseFloat(s[0]); coordinates.lat = parseFloat(s[1]); } else if (Array.isArray(near.near)) { @@ -1111,11 +1111,11 @@ function buildNearFilter(query, params) { coordinates = near.near; } - var props = ['maxDistance', 'minDistance']; + const props = ['maxDistance', 'minDistance']; // use mongodb default unit 'meters' rather than 'miles' - var unit = near.unit || 'meters'; + const unit = near.unit || 'meters'; - var queryValue = { + const queryValue = { near: { $geometry: { coordinates: [coordinates.lng, coordinates.lat], @@ -1130,15 +1130,16 @@ function buildNearFilter(query, params) { } }); - var property; + let property; if (near.mongoKey) { // if mongoKey is an Array, set the $near query at the right depth, following the Array if (Array.isArray(near.mongoKey)) { property = query.where; - for (var i = 0; i < near.mongoKey.length; i++) { - var subKey = near.mongoKey[i]; + let i; + for (i = 0; i < near.mongoKey.length; i++) { + const subKey = near.mongoKey[i]; if (near.mongoKey.hasOwnProperty(i + 1)) { if (!property.hasOwnProperty(subKey)) { @@ -1165,7 +1166,7 @@ function hasNearFilter(where) { // TODO: Optimize to return once a `near` key is found // instead of searching through everything - var isFound = false; + let isFound = false; searchForNear(where); @@ -1188,7 +1189,7 @@ function hasNearFilter(where) { }); } else if (typeof node === 'object') { Object.keys(node).forEach(function(key) { - var prop = node[key]; + const prop = node[key]; isFound = found(prop); @@ -1214,7 +1215,7 @@ MongoDB.prototype.getDatabaseColumnName = function(model, propName) { return propName; // missing model properties? } - var prop = model.properties[propName] || {}; + const prop = model.properties[propName] || {}; // console.log('getDatabaseColumnName', propName, prop); @@ -1255,8 +1256,8 @@ MongoDB.prototype.convertColumnNames = function(model, data, direction) { return data; // missing model properties? } - for (var propName in model.properties) { - var columnName = this.getDatabaseColumnName(model, propName); + for (const propName in model.properties) { + const columnName = this.getDatabaseColumnName(model, propName); // Copy keys/data if needed if (propName === columnName) { @@ -1293,23 +1294,23 @@ MongoDB.prototype.fromDatabaseToPropertyNames = function(model, data) { * @param {Function} [callback] The callback function */ MongoDB.prototype.all = function all(modelName, filter, options, callback) { - var self = this; + const self = this; if (self.debug) { debug('all', modelName, filter); } filter = filter || {}; - var idName = self.idName(modelName); - var query = {}; + const idName = self.idName(modelName); + let query = {}; if (filter.where) { query = self.buildWhere(modelName, filter.where, options); } - var fields = filter.fields; + let fields = filter.fields; // Convert custom column names fields = self.fromPropertyToDatabaseNames(modelName, fields); if (fields) { - var findOpts = {projection: fieldsArrayToObj(fields)}; + const findOpts = {projection: fieldsArrayToObj(fields)}; this.execute(modelName, 'find', query, findOpts, processResponse); } else { this.execute(modelName, 'find', query, processResponse); @@ -1320,14 +1321,14 @@ MongoDB.prototype.all = function all(modelName, filter, options, callback) { return callback(err); } - var collation = options && options.collation; + const collation = options && options.collation; if (collation) { cursor.collation(collation); } // don't apply sorting if dealing with a geo query if (!hasNearFilter(filter.where)) { - var order = self.buildSort(modelName, filter.order, options); + const order = self.buildSort(modelName, filter.order, options); cursor.sort(order); } @@ -1340,8 +1341,8 @@ MongoDB.prototype.all = function all(modelName, filter, options, callback) { cursor.skip(filter.offset); } - var shouldSetIdValue = idIncluded(fields, idName); - var deleteMongoId = !shouldSetIdValue || idName !== '_id'; + const shouldSetIdValue = idIncluded(fields, idName); + const deleteMongoId = !shouldSetIdValue || idName !== '_id'; cursor.toArray(function(err, data) { if (self.debug) { @@ -1350,7 +1351,7 @@ MongoDB.prototype.all = function all(modelName, filter, options, callback) { if (err) { return callback(err); } - var objs = data.map(function(o) { + const objs = data.map(function(o) { if (shouldSetIdValue) { self.setIdValue(modelName, o, o._id); } @@ -1388,7 +1389,7 @@ MongoDB.prototype.destroyAll = function destroyAll( options, callback ) { - var self = this; + const self = this; if (self.debug) { debug('destroyAll', modelName, where); } @@ -1404,7 +1405,7 @@ MongoDB.prototype.destroyAll = function destroyAll( if (self.debug) debug('destroyAll.callback', modelName, where, err, info); - var affectedCount = info.result ? info.result.n : undefined; + const affectedCount = info.result ? info.result.n : undefined; if (callback) { callback(err, {count: affectedCount}); @@ -1421,7 +1422,7 @@ MongoDB.prototype.destroyAll = function destroyAll( * */ MongoDB.prototype.count = function count(modelName, where, options, callback) { - var self = this; + const self = this; if (self.debug) { debug('count', modelName, where); } @@ -1447,7 +1448,7 @@ MongoDB.prototype.count = function count(modelName, where, options, callback) { */ MongoDB.prototype.replaceById = function replace(modelName, id, data, options, cb) { if (this.debug) debug('replace', modelName, id, data); - var oid = this.coerceId(modelName, id, options); + const oid = this.coerceId(modelName, id, options); this.replaceWithOptions(modelName, oid, data, {upsert: false}, function( err, data @@ -1457,8 +1458,8 @@ MongoDB.prototype.replaceById = function replace(modelName, id, data, options, c }; function errorIdNotFoundForReplace(idValue) { - var msg = 'Could not replace. Object with id ' + idValue + ' does not exist!'; - var error = new Error(msg); + const msg = 'Could not replace. Object with id ' + idValue + ' does not exist!'; + const error = new Error(msg); error.statusCode = error.status = 404; return error; } @@ -1472,8 +1473,8 @@ function errorIdNotFoundForReplace(idValue) { * @callback {Function} [cb] Callback function */ MongoDB.prototype.replaceWithOptions = function(modelName, id, data, options, cb) { - var self = this; - var idName = self.idName(modelName); + const self = this; + const idName = self.idName(modelName); delete data[idName]; this.execute(modelName, 'replaceOne', {_id: id}, data, options, function( err, @@ -1481,8 +1482,8 @@ MongoDB.prototype.replaceWithOptions = function(modelName, id, data, options, cb ) { debug('updateWithOptions.callback', modelName, {_id: id}, data, err, info); if (err) return cb && cb(err); - var result; - var cbInfo = {}; + let result; + const cbInfo = {}; if (info.result && info.result.n == 1) { result = data; delete result._id; @@ -1520,7 +1521,7 @@ MongoDB.prototype.updateAttributes = function updateAttrs( options, cb ) { - var self = this; + const self = this; data = self.toDatabase(modelName, data || {}); @@ -1540,8 +1541,8 @@ MongoDB.prototype.updateAttributes = function updateAttrs( return; } - var oid = self.coerceId(modelName, id, options); - var idName = this.idName(modelName); + const oid = self.coerceId(modelName, id, options); + const idName = this.idName(modelName); this.execute( modelName, @@ -1557,7 +1558,7 @@ MongoDB.prototype.updateAttributes = function updateAttrs( if (self.debug) { debug('updateAttributes.callback', modelName, id, err, result); } - var object = result && result.value; + const object = result && result.value; if (!err && !object) { // No result err = errorIdNotFoundForUpdate(modelName, id); @@ -1574,8 +1575,8 @@ MongoDB.prototype.updateAttributes = function updateAttrs( }; function errorIdNotFoundForUpdate(modelvalue, idValue) { - var msg = 'No ' + modelvalue + ' found for id ' + idValue; - var error = new Error(msg); + const msg = 'No ' + modelvalue + ' found for id ' + idValue; + const error = new Error(msg); error.statusCode = error.status = 404; return error; } @@ -1594,11 +1595,11 @@ MongoDB.prototype.update = MongoDB.prototype.updateAll = function updateAll( options, cb ) { - var self = this; + const self = this; if (self.debug) { debug('updateAll', modelName, where, data); } - var idName = this.idName(modelName); + const idName = this.idName(modelName); where = self.buildWhere(modelName, where, options); @@ -1620,7 +1621,7 @@ MongoDB.prototype.update = MongoDB.prototype.updateAll = function updateAll( if (self.debug) debug('updateAll.callback', modelName, where, data, err, info); - var affectedCount = info.result ? info.result.n : undefined; + const affectedCount = info.result ? info.result.n : undefined; if (cb) { cb(err, {count: affectedCount}); @@ -1654,7 +1655,7 @@ MongoDB.prototype.disconnect = function(cb) { * @param {Function} [cb] The callback function */ MongoDB.prototype.autoupdate = function(models, cb) { - var self = this; + const self = this; if (self.db) { if (self.debug) { debug('autoupdate'); @@ -1670,18 +1671,18 @@ MongoDB.prototype.autoupdate = function(models, cb) { models = models || Object.keys(self._models); - var enableGeoIndexing = this.settings.enableGeoIndexing === true; + const enableGeoIndexing = this.settings.enableGeoIndexing === true; async.each( models, function(modelName, modelCallback) { - var indexes = self._models[modelName].settings.indexes || []; - var indexList = []; - var index = {}; - var options = {}; + const indexes = self._models[modelName].settings.indexes || []; + let indexList = []; + let index = {}; + let options = {}; if (typeof indexes === 'object') { - for (var indexName in indexes) { + for (const indexName in indexes) { index = indexes[indexName]; if (index.keys) { // The index object has keys @@ -1700,9 +1701,9 @@ MongoDB.prototype.autoupdate = function(models, cb) { } else if (Array.isArray(indexes)) { indexList = indexList.concat(indexes); } - var properties = self._models[modelName].properties; + const properties = self._models[modelName].properties; /* eslint-disable one-var */ - for (var p in properties) { + for (const p in properties) { if (properties[p].index) { index = {}; index[p] = 1; // Add the index key @@ -1734,7 +1735,7 @@ MongoDB.prototype.autoupdate = function(models, cb) { properties[p].type && properties[p].type.name === 'GeoPoint' ) { - var indexType = + const indexType = typeof properties[p].index === 'string' ? properties[p].index : '2dsphere'; @@ -1789,7 +1790,7 @@ MongoDB.prototype.autoupdate = function(models, cb) { * @param {Function} [cb] The callback function */ MongoDB.prototype.automigrate = function(models, cb) { - var self = this; + const self = this; if (self.db) { if (self.debug) { debug('automigrate'); @@ -1809,7 +1810,7 @@ MongoDB.prototype.automigrate = function(models, cb) { async.eachSeries( models, function(modelName, modelCallback) { - var collectionName = self.collectionName(modelName); + const collectionName = self.collectionName(modelName); if (self.debug) { debug('drop collection %s for model %s', collectionName, modelName); } @@ -1855,7 +1856,7 @@ MongoDB.prototype.automigrate = function(models, cb) { }; MongoDB.prototype.ping = function(cb) { - var self = this; + const self = this; if (self.db) { this.db.collection('dummy').findOne({_id: 1}, cb); } else { @@ -1881,9 +1882,9 @@ MongoDB.prototype.isObjectIDProperty = function(modelName, prop, value, options) ) { return true; } else if ('string' === typeof value) { - var settings = this._models[modelName] && this._models[modelName].settings; + const settings = this._models[modelName] && this._models[modelName].settings; options = options || {}; - var strict = + const strict = (settings && settings.strictObjectIDCoercion) || this.settings.strictObjectIDCoercion || options.strictObjectIDCoercion; @@ -1922,20 +1923,20 @@ exports.sanitizeFilter = sanitizeFilter; * @param {Function} [callback] The callback function */ function optimizedFindOrCreate(modelName, filter, data, options, callback) { - var self = this; + const self = this; if (self.debug) { debug('findOrCreate', modelName, filter, data); } if (!callback) callback = options; - var idValue = self.getIdValue(modelName, data); - var idName = self.idName(modelName); + const idValue = self.getIdValue(modelName, data); + const idName = self.idName(modelName); if (idValue == null) { delete data[idName]; // Allow MongoDB to generate the id } else { - var oid = self.coerceId(modelName, idValue, options); // Is it an Object ID? + const oid = self.coerceId(modelName, idValue, options); // Is it an Object ID? data._id = oid; // Set it to _id if (idName !== '_id') { delete data[idName]; @@ -1943,10 +1944,10 @@ function optimizedFindOrCreate(modelName, filter, data, options, callback) { } filter = filter || {}; - var query = {}; + let query = {}; if (filter.where) { if (filter.where[idName]) { - var id = filter.where[idName]; + let id = filter.where[idName]; delete filter.where[idName]; id = self.coerceId(modelName, id, options); filter.where._id = id; @@ -1954,9 +1955,9 @@ function optimizedFindOrCreate(modelName, filter, data, options, callback) { query = self.buildWhere(modelName, filter.where, options); } - var sort = self.buildSort(modelName, filter.order, options); + const sort = self.buildSort(modelName, filter.order, options); - var projection = fieldsArrayToObj(filter.fields); + const projection = fieldsArrayToObj(filter.fields); this.collection(modelName).findOneAndUpdate( query, @@ -1970,8 +1971,8 @@ function optimizedFindOrCreate(modelName, filter, data, options, callback) { return callback(err); } - var value = result.value; - var created = !!result.lastErrorObject.upserted; + let value = result.value; + const created = !!result.lastErrorObject.upserted; if (created && (value == null || Object.keys(value).length == 0)) { value = data; diff --git a/lib/test-utils.js b/lib/test-utils.js index 67642cfce..95bdbbd0e 100644 --- a/lib/test-utils.js +++ b/lib/test-utils.js @@ -9,18 +9,18 @@ exports.getDistanceBetweenPoints = function getDistanceBetweenPoints( point1, point2 ) { - var R = 6371; // Radius of the earth in km - var dLat = deg2rad(point2.lat - point1.lat); // deg2rad below - var dLon = deg2rad(point2.lng - point1.lng); - var a = + const R = 6371; // Radius of the earth in km + const dLat = deg2rad(point2.lat - point1.lat); // deg2rad below + const dLon = deg2rad(point2.lng - point1.lng); + const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(deg2rad(point1.lat)) * Math.cos(deg2rad(point2.lat)) * Math.sin(dLon / 2) * Math.sin(dLon / 2); - var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); - var d = R * c; // Distance in km + const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); + const d = R * c; // Distance in km return d; }; diff --git a/package.json b/package.json index 20db5abc2..01c9c4c32 100644 --- a/package.json +++ b/package.json @@ -38,7 +38,7 @@ "benchmark": "^2.1.4", "bluebird": "^3.5.4", "eslint": "^5.1.0", - "eslint-config-loopback": "^10.0.0", + "eslint-config-loopback": "^13.0.0", "juggler-v3": "file:./deps/juggler-v3", "juggler-v4": "file:./deps/juggler-v4", "loopback-datasource-juggler": "^3.0.0 || ^4.0.0", diff --git a/test/connector-functions.test.js b/test/connector-functions.test.js index f28fd51b4..2c513d625 100644 --- a/test/connector-functions.test.js +++ b/test/connector-functions.test.js @@ -6,10 +6,10 @@ 'use strict'; // This test written in mocha+should.js -var should = require('./init.js'); +const should = require('./init.js'); describe('connector function - findById', function() { - var db, TestAlias, sampleId; + let db, TestAlias, sampleId; before(function(done) { db = global.getDataSource(); TestAlias = db.define('TestAlias', {foo: {type: String}}); diff --git a/test/decimal.test.js b/test/decimal.test.js index 67badbeff..f8efac793 100644 --- a/test/decimal.test.js +++ b/test/decimal.test.js @@ -9,12 +9,12 @@ require('./init.js'); const promisify = require('bluebird').promisify; const Decimal128 = require('mongodb').Decimal128; -var db, OrderDecimal; +let db, OrderDecimal; describe('model with decimal property', function() { before(function(done) { db = global.getDataSource(); - var propertyDef = { + const propertyDef = { count: { type: String, mongodb: { @@ -118,14 +118,14 @@ describe('model with decimal property', function() { updateOnLoad: true, }); - var createData = { + const createData = { 'randomReview': [ '3.5', '4.5', '4.0', ], }; - var updateData = { + const updateData = { 'randomReview': [ '5.5', '5.5', diff --git a/test/id.test.js b/test/id.test.js index 6b7ffd2cf..c7b218b73 100644 --- a/test/id.test.js +++ b/test/id.test.js @@ -6,10 +6,10 @@ 'use strict'; require('./init.js'); -var ds = global.getDataSource(); +const ds = global.getDataSource(); describe('mongodb custom id name', function() { - var Customer = ds.createModel( + const Customer = ds.createModel( 'customer', { seq: {type: Number, id: true}, @@ -66,7 +66,7 @@ describe('mongodb custom id name', function() { }); describe('mongodb string id', function() { - var Customer = ds.createModel( + const Customer = ds.createModel( 'customer2', { seq: {type: String, id: true}, @@ -76,7 +76,7 @@ describe('mongodb string id', function() { }, {forceId: false} ); - var customer1, customer2; + let customer1, customer2; before(function(done) { Customer.deleteAll(done); @@ -93,7 +93,7 @@ describe('mongodb string id', function() { function(err, customer) { customer.seq.should.equal('1'); customer1 = customer; - var customer2Id = new ds.ObjectID().toString(); + const customer2Id = new ds.ObjectID().toString(); Customer.create( { seq: customer2Id, @@ -140,7 +140,7 @@ describe('mongodb string id', function() { }); describe('mongodb default id type', function() { - var Account = ds.createModel( + const Account = ds.createModel( 'account', { seq: {id: true, generated: true}, @@ -155,7 +155,7 @@ describe('mongodb default id type', function() { Account.deleteAll(done); }); - var id; + let id; it('should generate id value for create', function(done) { Account.create( { @@ -197,7 +197,7 @@ describe('mongodb default id type', function() { }); describe('mongodb default id name', function() { - var Customer1 = ds.createModel( + const Customer1 = ds.createModel( 'customer1', {name: String, emails: [String], age: Number}, {forceId: false} diff --git a/test/init.js b/test/init.js index d114969e9..5311bf2d5 100644 --- a/test/init.js +++ b/test/init.js @@ -7,11 +7,11 @@ module.exports = require('should'); -var juggler = require('loopback-datasource-juggler'); -var DataSource = juggler.DataSource; +const juggler = require('loopback-datasource-juggler'); +let DataSource = juggler.DataSource; -var TEST_ENV = process.env.TEST_ENV || 'test'; -var config = require('rc')('loopback', {test: {mongodb: {}}})[TEST_ENV] +const TEST_ENV = process.env.TEST_ENV || 'test'; +let config = require('rc')('loopback', {test: {mongodb: {}}})[TEST_ENV] .mongodb; config = { @@ -25,7 +25,7 @@ config = { global.config = config; -var db; +let db; global.getDataSource = global.getSchema = function(customConfig, customClass) { const ctor = customClass || DataSource; db = new ctor(require('../'), customConfig || config); @@ -38,7 +38,7 @@ global.getDataSource = global.getSchema = function(customConfig, customClass) { global.resetDataSourceClass = function(ctor) { DataSource = ctor || juggler.DataSource; - var promise = db ? db.disconnect() : Promise.resolve(); + const promise = db ? db.disconnect() : Promise.resolve(); db = undefined; return promise; }; diff --git a/test/mongodb.test.js b/test/mongodb.test.js index dec88b771..c8877f933 100644 --- a/test/mongodb.test.js +++ b/test/mongodb.test.js @@ -6,16 +6,16 @@ 'use strict'; // This test written in mocha+should.js -var semver = require('semver'); -var should = require('./init.js'); -var testUtils = require('../lib/test-utils'); -var async = require('async'); -var sinon = require('sinon'); -var sanitizeFilter = require('../lib/mongodb').sanitizeFilter; +const semver = require('semver'); +const should = require('./init.js'); +const testUtils = require('../lib/test-utils'); +const async = require('async'); +const sinon = require('sinon'); +const sanitizeFilter = require('../lib/mongodb').sanitizeFilter; -var GeoPoint = require('loopback-datasource-juggler').GeoPoint; +const GeoPoint = require('loopback-datasource-juggler').GeoPoint; -var Superhero, +let Superhero, User, Post, Product, @@ -34,12 +34,12 @@ var Superhero, describe('lazyConnect', function() { it('should skip connect phase (lazyConnect = true)', function(done) { - var ds = global.getDataSource({ + const ds = global.getDataSource({ host: '127.0.0.1', port: 4, lazyConnect: true, }); - var errTimeout = setTimeout(function() { + const errTimeout = setTimeout(function() { done(); }, 2000); @@ -50,7 +50,7 @@ describe('lazyConnect', function() { }); it('should report connection error (lazyConnect = false)', function(done) { - var ds = global.getDataSource({ + const ds = global.getDataSource({ host: '127.0.0.1', port: 4, lazyConnect: false, @@ -65,7 +65,7 @@ describe('lazyConnect', function() { }); it('should connect on execute (lazyConnect = true)', function(done) { - var ds = global.getDataSource({ + const ds = global.getDataSource({ host: '127.0.0.1', port: global.config.port, lazyConnect: true, @@ -90,7 +90,7 @@ describe('lazyConnect', function() { }); it('should reconnect on execute when disconnected (lazyConnect = true)', function(done) { - var ds = global.getDataSource({ + const ds = global.getDataSource({ host: '127.0.0.1', port: global.config.port, lazyConnect: true, @@ -108,7 +108,7 @@ describe('lazyConnect', function() { {value: 'test value'}, function(err, success) { if (err) done(err); - var id = success.insertedId; + const id = success.insertedId; ds.connector.should.have.property('db'); ds.connector.db.should.have.property('topology'); ds.connector.db.topology.should.have.property('isDestroyed'); @@ -358,7 +358,7 @@ describe('mongodb connector', function() { }); it('should report connection errors with invalid config', function(done) { - var ds = global.getDataSource({ + const ds = global.getDataSource({ host: 'localhost', port: 4, // unassigned by IANA }); @@ -371,10 +371,10 @@ describe('mongodb connector', function() { }); it('ignores invalid option', function(done) { - var configWithInvalidOption = Object.assign({}, global.config, { + const configWithInvalidOption = Object.assign({}, global.config, { invalidOption: 'invalid', }); - var ds = global.getDataSource(configWithInvalidOption); + const ds = global.getDataSource(configWithInvalidOption); ds.ping(function(err) { if (err) return done(err); ds.disconnect(done); @@ -382,9 +382,9 @@ describe('mongodb connector', function() { }); it('accepts database from the url', function(done) { - var cfg = JSON.parse(JSON.stringify(global.config)); + const cfg = JSON.parse(JSON.stringify(global.config)); delete cfg.database; - var ds = global.getDataSource(cfg); + const ds = global.getDataSource(cfg); ds.ping(function(err) { if (err) return done(err); ds.disconnect(done); @@ -392,13 +392,13 @@ describe('mongodb connector', function() { }); it('should prioritize to the database given in the url property', function(done) { - var cfg = JSON.parse(JSON.stringify(global.config)); - var testDb = 'lb-ds-overriden-test-1'; + const cfg = JSON.parse(JSON.stringify(global.config)); + const testDb = 'lb-ds-overriden-test-1'; cfg.url = 'mongodb://' + cfg.host + ':' + cfg.port + '/' + testDb; - var ds = global.getDataSource(cfg); + const ds = global.getDataSource(cfg); ds.once('connected', function() { - var db = ds.connector.db; - var validationError = null; + const db = ds.connector.db; + let validationError = null; try { db.should.have.property('databaseName', testDb); // check the db name in the db instance } catch (err) { @@ -418,7 +418,7 @@ describe('mongodb connector', function() { }); describe('order filters', function() { - var data = [ + const data = [ { id: 1, title: 'Senior Software Developer', @@ -460,13 +460,13 @@ describe('mongodb connector', function() { context('using buildSort directly', function() { it('sort in descending order', function(done) { - var sort = db.connector.buildSort('Employee', 'id DESC'); + const sort = db.connector.buildSort('Employee', 'id DESC'); sort.should.have.property('_id'); sort._id.should.equal(-1); done(); }); it('sort in ascending order', function(done) { - var sort = db.connector.buildSort('Employee', 'id ASC'); + const sort = db.connector.buildSort('Employee', 'id ASC'); sort.should.have.property('_id'); sort._id.should.equal(1); done(); @@ -505,7 +505,7 @@ describe('mongodb connector', function() { .collection('User') .indexInformation(function(err, result) { /* eslint-disable camelcase */ - var indexes = { + const indexes = { _id_: [['_id', 1]], name_age_index: [['name', 1], ['age', -1]], age_index: [['age', -1]], @@ -523,7 +523,7 @@ describe('mongodb connector', function() { db.automigrate('Superhero', function() { db.connector.db.collection('sh').indexInformation(function(err, result) { /* eslint-disable camelcase */ - var indexes = { + const indexes = { _id_: [['_id', 1]], geojson_location_geometry: [['location.geometry', '2dsphere']], power_1: [['power', 1]], @@ -542,7 +542,7 @@ describe('mongodb connector', function() { db.automigrate('Category', function() { db.connector.db.collection('Category').indexes(function(err, result) { if (err) return done(err); - var indexes = [ + const indexes = [ {name: '_id_', key: {_id: 1}}, {name: 'title_1', key: {title: 1}}, {name: 'title_case_insensitive', key: {title: 1}, collation: {locale: 'en', strength: 1}}, @@ -660,7 +660,7 @@ describe('mongodb connector', function() { }); it('all should return object (with `_id` as defined id) with an _id instanceof ObjectID', function(done) { - var post = new PostWithObjectId({title: 'a', content: 'AAA'}); + const post = new PostWithObjectId({title: 'a', content: 'AAA'}); post.save(function(err, post) { PostWithObjectId.all({where: {title: 'a'}}, function(err, posts) { should.not.exist(err); @@ -676,7 +676,7 @@ describe('mongodb connector', function() { }); it('all return should honor filter.fields, with `_id` as defined id', function(done) { - var post = new PostWithObjectId({title: 'a', content: 'AAA'}); + const post = new PostWithObjectId({title: 'a', content: 'AAA'}); post.save(function(err, post) { PostWithObjectId.all( {fields: ['title'], where: {title: 'a'}}, @@ -689,12 +689,13 @@ describe('mongodb connector', function() { should.not.exist(post._id); done(); - }); + } + ); }); }); it('all return should honor filter.fields with `_id` selected', function(done) { - var post = new PostWithObjectId({title: 'a', content: 'AAA'}); + const post = new PostWithObjectId({title: 'a', content: 'AAA'}); post.save(function(err, post) { PostWithObjectId.all( {fields: ['_id', 'content'], where: {title: 'a'}}, @@ -908,8 +909,8 @@ describe('mongodb connector', function() { }); it('should invoke hooks', function(done) { - var events = []; - var connector = Post.getDataSource().connector; + const events = []; + const connector = Post.getDataSource().connector; connector.observe('before execute', function(ctx, next) { ctx.req.command.should.be.String(); ctx.req.params.should.be.Array(); @@ -1140,7 +1141,7 @@ describe('mongodb connector', function() { }); }); - var describeMongo26 = describe; + let describeMongo26 = describe; if ( process.env.MONGODB_VERSION && !semver.satisfies(process.env.MONGODB_VERSION, '~2.6.0') @@ -1312,7 +1313,7 @@ describe('mongodb connector', function() { it('should be possible to enable using options - even if globally disabled', function(done) { User.dataSource.settings.allowExtendedOperators = false; - var options = {allowExtendedOperators: true}; + const options = {allowExtendedOperators: true}; User.create({name: 'Al', age: 31, email: 'al@strongloop'}, function( err1, createdusers1 @@ -1343,7 +1344,7 @@ describe('mongodb connector', function() { it('should be possible to disable using options - even if globally disabled', function(done) { User.dataSource.settings.allowExtendedOperators = true; - var options = {allowExtendedOperators: false}; + const options = {allowExtendedOperators: false}; User.create({name: 'Al', age: 31, email: 'al@strongloop'}, function( err1, createdusers1 @@ -1667,7 +1668,7 @@ describe('mongodb connector', function() { Product.create( {name: 'bread', price: 100, pricehistory: [{'2014-11-11': 90}]}, function(err, product) { - var newattributes = { + const newattributes = { $set: {description: 'goes well with butter'}, $addToSet: {pricehistory: {'2014-12-12': 110}}, }; @@ -1746,7 +1747,7 @@ describe('mongodb connector', function() { pricehistory: [{'2014-11-11': 90}, {'2014-10-10': 80}], }, function(err, product) { - var newattributes = { + const newattributes = { $set: {description: 'goes well with butter'}, $addToSet: {pricehistory: {'2014-12-12': 110}}, }; @@ -1781,7 +1782,7 @@ describe('mongodb connector', function() { ], }, function(err, product) { - var newattributes = { + const newattributes = { $set: {description: 'goes well with butter'}, $addToSet: {pricehistory: 1}, }; @@ -1845,7 +1846,7 @@ describe('mongodb connector', function() { Product.create( {name: 'bread', price: 100, pricehistory: [70, 80, 90, 100]}, function(err, product) { - var newattributes = { + const newattributes = { $set: {description: 'goes well with butter'}, $pull: {pricehistory: {$gte: 90}}, }; @@ -1895,7 +1896,7 @@ describe('mongodb connector', function() { Product.create( {name: 'bread', price: 100, pricehistory: [70, 80, 90, 100]}, function(err, product) { - var newattributes = { + const newattributes = { $set: {description: 'goes well with butter'}, $pullAll: {pricehistory: [80, 100]}, }; @@ -1950,7 +1951,7 @@ describe('mongodb connector', function() { pricehistory: [{'2014-11-11': 90}, {'2014-10-10': 80}], }, function(err, product) { - var newattributes = { + const newattributes = { $set: {description: 'goes well with butter'}, $push: {pricehistory: {'2014-10-10': 80}}, }; @@ -2177,7 +2178,7 @@ describe('mongodb connector', function() { }); it('updateOrCreate should create a new instance if it does not exist', function(done) { - var post = {id: '123', title: 'a', content: 'AAA'}; + const post = {id: '123', title: 'a', content: 'AAA'}; Post.updateOrCreate(post, function(err, p) { should.not.exist(err); p.title.should.be.equal(post.title); @@ -2239,7 +2240,7 @@ describe('mongodb connector', function() { }); it('save should create a new instance if it does not exist', function(done) { - var post = new Post({id: '123', title: 'a', content: 'AAA'}); + const post = new Post({id: '123', title: 'a', content: 'AAA'}); post.save(post, function(err, p) { should.not.exist(err); p.title.should.be.equal(post.title); @@ -2258,7 +2259,7 @@ describe('mongodb connector', function() { }); }); it('all should return object with an id, which is instanceof ObjectID, but not mongodb _id', function(done) { - var post = new Post({title: 'a', content: 'AAA'}); + const post = new Post({title: 'a', content: 'AAA'}); post.save(function(err, post) { Post.all({where: {title: 'a'}}, function(err, posts) { should.not.exist(err); @@ -2275,7 +2276,7 @@ describe('mongodb connector', function() { }); it('all return should honor filter.fields', function(done) { - var post = new Post({title: 'b', content: 'BBB'}); + const post = new Post({title: 'b', content: 'BBB'}); post.save(function(err, post) { db.connector.all( 'Post', @@ -2297,8 +2298,8 @@ describe('mongodb connector', function() { }); it('create should convert id from ObjectID to string', function(done) { - var oid = new db.ObjectID(); - var sid = oid.toString(); + const oid = new db.ObjectID(); + const sid = oid.toString(); PostWithStringId.create({id: oid, title: 'c', content: 'CCC'}, function( err, post @@ -2315,8 +2316,8 @@ describe('mongodb connector', function() { }); it('create should convert id from string to ObjectID', function(done) { - var oid = new db.ObjectID(); - var sid = oid.toString(); + const oid = new db.ObjectID(); + const sid = oid.toString(); Post.create({id: sid, title: 'c', content: 'CCC'}, function(err, post) { post.id.should.be.an.instanceOf(db.ObjectID); Post.findById(sid, function(err, post) { @@ -2351,7 +2352,7 @@ describe('mongodb connector', function() { }); it('create should support renamed column names (using property syntax first)', function(done) { - var oid = new db.ObjectID().toString(); + const oid = new db.ObjectID().toString(); PostWithStringId.create({id: oid, title: 'c', content: 'CCC'}, function( err, post @@ -2372,7 +2373,7 @@ describe('mongodb connector', function() { }); it('create should support renamed column names (using db syntax first)', function(done) { - var oid = new db.ObjectID().toString(); + const oid = new db.ObjectID().toString(); PostWithStringIdAndRenamedColumns.create( { id: oid, @@ -2397,10 +2398,10 @@ describe('mongodb connector', function() { }); describe('geo queries', function() { - var geoDb, PostWithLocation, createLocationPost; + let geoDb, PostWithLocation, createLocationPost; before(function() { - var config = JSON.parse(JSON.stringify(global.config)); // clone config + const config = JSON.parse(JSON.stringify(global.config)); // clone config config.enableGeoIndexing = true; geoDb = global.getDataSource(config); @@ -2410,7 +2411,7 @@ describe('mongodb connector', function() { location: {type: GeoPoint, index: true}, }); createLocationPost = function(far) { - var point; + let point; if (far) { point = new GeoPoint({ lat: 31.230416, @@ -2433,7 +2434,7 @@ describe('mongodb connector', function() { }); it('create should convert geopoint to geojson', function(done) { - var point = new GeoPoint({lat: 1.243, lng: 20.4}); + const point = new GeoPoint({lat: 1.243, lng: 20.4}); PostWithLocation.create({location: point}, function(err, post) { should.not.exist(err); @@ -2445,11 +2446,11 @@ describe('mongodb connector', function() { }); it('find should be able to query by location', function(done) { - var coords = {lat: 1.25, lng: 20.2}; + const coords = {lat: 1.25, lng: 20.2}; geoDb.autoupdate(function(err) { - var createPost = function(callback) { - var point = new GeoPoint({ + const createPost = function(callback) { + const point = new GeoPoint({ lat: Math.random() * 180 - 90, lng: Math.random() * 360 - 180, }); @@ -2479,9 +2480,9 @@ describe('mongodb connector', function() { should.not.exist(err); should.exist(results); - var dist = 0; + let dist = 0; results.forEach(function(result) { - var currentDist = testUtils.getDistanceBetweenPoints( + const currentDist = testUtils.getDistanceBetweenPoints( coords, result.location ); @@ -2498,11 +2499,11 @@ describe('mongodb connector', function() { }); it('find should be queryable using locations with deep/multiple keys', function(done) { - var coords = {lat: 1.25, lng: 20.2}; + const coords = {lat: 1.25, lng: 20.2}; geoDb.autoupdate(function(err) { - var heroNumber = 0; - var powers = ['fly', 'lasers', 'strength', 'drink']; + let heroNumber = 0; + const powers = ['fly', 'lasers', 'strength', 'drink']; function createSuperheroWithLocation(callback) { heroNumber++; @@ -2553,9 +2554,9 @@ describe('mongodb connector', function() { results.should.have.length(1); - var dist = 0; + let dist = 0; results.forEach(function(result) { - var currentDist = testUtils.getDistanceBetweenPoints(coords, { + const currentDist = testUtils.getDistanceBetweenPoints(coords, { lng: result.location.geometry.coordinates[0], lat: result.location.geometry.coordinates[1], }); @@ -2572,7 +2573,7 @@ describe('mongodb connector', function() { }); it('find should be able to query by location via near with maxDistance', function(done) { - var coords = {lat: 30.274085, lng: 120.15507000000002}; + const coords = {lat: 30.274085, lng: 120.15507000000002}; geoDb.autoupdate(function(err) { async.parallel( @@ -2597,9 +2598,9 @@ describe('mongodb connector', function() { function(err, results) { if (err) return done(err); results.length.should.be.equal(3); - var dist = 0; + let dist = 0; results.forEach(function(result) { - var currentDist = testUtils.getDistanceBetweenPoints( + const currentDist = testUtils.getDistanceBetweenPoints( coords, result.location ); @@ -2616,7 +2617,7 @@ describe('mongodb connector', function() { }); it('find should be able to query by location via near with minDistance set', function(done) { - var coords = {lat: 30.274085, lng: 120.15507000000002}; + const coords = {lat: 30.274085, lng: 120.15507000000002}; geoDb.autoupdate(function(err) { async.parallel( [ @@ -2640,9 +2641,9 @@ describe('mongodb connector', function() { function(err, results) { if (err) return done(err); results.length.should.be.equal(1); - var dist = 0; + let dist = 0; results.forEach(function(result) { - var currentDist = testUtils.getDistanceBetweenPoints( + const currentDist = testUtils.getDistanceBetweenPoints( coords, result.location ); @@ -2658,10 +2659,10 @@ describe('mongodb connector', function() { }); it('find should be able to set unit when query location via near', function(done) { - var coords = {lat: 30.274085, lng: 120.15507000000002}; + const coords = {lat: 30.274085, lng: 120.15507000000002}; geoDb.autoupdate(function(err) { - var queryLocation = function( + const queryLocation = function( distance, unit, distanceInMeter, @@ -2682,7 +2683,7 @@ describe('mongodb connector', function() { if (err) return done(err); results.length.should.be.equal(numOfResult); results.forEach(function(result) { - var currentDist = testUtils.getDistanceBetweenPoints( + const currentDist = testUtils.getDistanceBetweenPoints( coords, result.location ); @@ -3131,31 +3132,31 @@ describe('mongodb connector', function() { }); it('should export the MongoDB function', function() { - var module = require('../'); + const module = require('../'); module.MongoDB.should.be.an.instanceOf(Function); }); it('should export the ObjectID function', function() { - var module = require('../'); + const module = require('../'); module.ObjectID.should.be.an.instanceOf(Function); }); it('should export the generateMongoDBURL function', function() { - var module = require('../'); + const module = require('../'); module.generateMongoDBURL.should.be.an.instanceOf(Function); }); describe('Test generateMongoDBURL function', function() { - var module = require('../'); + const module = require('../'); context('should return correct mongodb url ', function() { it('when only passing in database', function() { - var options = { + const options = { database: 'fakeDatabase', }; module.generateMongoDBURL(options).should.be.eql('mongodb://127.0.0.1:27017/fakeDatabase'); }); it('when protocol is mongodb and no username/password', function() { - var options = { + const options = { protocol: 'mongodb', hostname: 'fakeHostname', port: 9999, @@ -3164,7 +3165,7 @@ describe('mongodb connector', function() { module.generateMongoDBURL(options).should.be.eql('mongodb://fakeHostname:9999/fakeDatabase'); }); it('when protocol is mongodb and has username/password', function() { - var options = { + const options = { protocol: 'mongodb', hostname: 'fakeHostname', port: 9999, @@ -3175,7 +3176,7 @@ describe('mongodb connector', function() { module.generateMongoDBURL(options).should.be.eql('mongodb://fakeUsername:fakePassword@fakeHostname:9999/fakeDatabase'); }); it('when protocol is mongodb+srv and no username/password', function() { - var options = { + const options = { protocol: 'mongodb+srv', hostname: 'fakeHostname', port: 9999, @@ -3185,7 +3186,7 @@ describe('mongodb connector', function() { module.generateMongoDBURL(options).should.be.eql('mongodb+srv://fakeHostname/fakeDatabase'); }); it('when protocol is mongodb+srv and has username/password', function() { - var options = { + const options = { protocol: 'mongodb+srv', hostname: 'fakeHostname', port: 9999, @@ -3200,7 +3201,7 @@ describe('mongodb connector', function() { }); context('fieldsArrayToObj', function() { - var fieldsArrayToObj = require('../').fieldsArrayToObj; + const fieldsArrayToObj = require('../').fieldsArrayToObj; it('should export the fieldsArrayToObj function', function() { fieldsArrayToObj.should.be.an.instanceOf(Function); }); diff --git a/test/objectid.test.js b/test/objectid.test.js index 67807a3fd..5d31a1258 100644 --- a/test/objectid.test.js +++ b/test/objectid.test.js @@ -7,7 +7,7 @@ require('./init.js'); -var ds, Book, Chapter; +let ds, Book, Chapter; describe('ObjectID', function() { before(function() { @@ -32,26 +32,26 @@ describe('ObjectID', function() { }); it('should convert 24 byte hex string as ObjectID', function() { - var ObjectID = ds.connector.getDefaultIdType(); - var str = '52fcef5c0325ace8dcb7a0bd'; + const ObjectID = ds.connector.getDefaultIdType(); + const str = '52fcef5c0325ace8dcb7a0bd'; ObjectID(str).should.be.an.instanceOf(ds.ObjectID); }); it('should not convert 12 byte string as ObjectID', function() { - var ObjectID = ds.connector.getDefaultIdType(); - var str = 'line-by-line'; + const ObjectID = ds.connector.getDefaultIdType(); + const str = 'line-by-line'; ObjectID(str).should.be.equal(str); }); it('should keep mongodb ObjectID as is', function() { - var ObjectID = ds.connector.getDefaultIdType(); - var id = new ds.ObjectID(); + const ObjectID = ds.connector.getDefaultIdType(); + const id = new ds.ObjectID(); ObjectID(id).should.be.an.instanceOf(ds.ObjectID); }); it('should keep non-string id as it', function() { - var ObjectID = ds.connector.getDefaultIdType(); - var id = 123; + const ObjectID = ds.connector.getDefaultIdType(); + const id = 123; ObjectID(id).should.be.equal(123); });