diff --git a/benchmarks/benchjs/delete.js b/benchmarks/benchjs/delete.js index f5015a7cace..62287084602 100644 --- a/benchmarks/benchjs/delete.js +++ b/benchmarks/benchjs/delete.js @@ -68,13 +68,13 @@ mongoose.connect('mongodb://localhost/mongoose-bench', function (err) { function closeDB() { User.count(function (err, res) { - if (res != 0) { + if (res !== 0) { console.log('Still mongoose entries left...'); } mongoose.disconnect(); }); user.count({}, function (err, res) { - if (res != 0) { + if (res !== 0) { console.log('Still driver entries left...'); } if (err) { diff --git a/benchmarks/benchjs/multiop.js b/benchmarks/benchjs/multiop.js index 3423525a890..13da718b9f4 100644 --- a/benchmarks/benchjs/multiop.js +++ b/benchmarks/benchjs/multiop.js @@ -190,7 +190,7 @@ mongoose.connect('mongodb://localhost/mongoose-bench', function (err) { } --count || deferred.resolve(); }); - if (i % 15 == 0) { + if (i % 15 === 0) { var nData = utils.clone(data); User.create(nData, function (err) { if (err) { @@ -212,7 +212,7 @@ mongoose.connect('mongodb://localhost/mongoose-bench', function (err) { } --count || deferred.resolve(); }); - if (i % 15 == 0) { + if (i % 15 === 0) { var nData = utils.clone(data); user.insert(nData, function (err) { if (err) { @@ -234,7 +234,7 @@ mongoose.connect('mongodb://localhost/mongoose-bench', function (err) { } --count || deferred.resolve(); }); - if (i % 15 == 0) { + if (i % 15 === 0) { var nData = utils.clone(blogData); BlogPost.create(nData, function (err) { if (err) { @@ -256,7 +256,7 @@ mongoose.connect('mongodb://localhost/mongoose-bench', function (err) { } --count || deferred.resolve(); }); - if (i % 15 == 0) { + if (i % 15 === 0) { var nData = utils.clone(blogData); blogpost.insert(nData, function (err) { if (err) { @@ -280,7 +280,7 @@ mongoose.connect('mongodb://localhost/mongoose-bench', function (err) { } --count || deferred.resolve(); }); - if (i % 15 == 0) { + if (i % 15 === 0) { User.findOne({_id: getNextmId()}, function (err) { if (err) { throw err; @@ -303,7 +303,7 @@ mongoose.connect('mongodb://localhost/mongoose-bench', function (err) { } --count || deferred.resolve(); }); - if (i % 15 == 0) { + if (i % 15 === 0) { user.findOne({_id: getNextdId()}, function (err) { if (err) { throw err; @@ -326,7 +326,7 @@ mongoose.connect('mongodb://localhost/mongoose-bench', function (err) { } --count || deferred.resolve(); }); - if (i % 15 == 0) { + if (i % 15 === 0) { BlogPost.findOne({_id: getNextbmId()}, function (err) { if (err) { throw err; @@ -349,7 +349,7 @@ mongoose.connect('mongodb://localhost/mongoose-bench', function (err) { } --count || deferred.resolve(); }); - if (i % 15 == 0) { + if (i % 15 === 0) { blogpost.findOne({_id: getNextbdId()}, function (err) { if (err) { throw err; @@ -384,7 +384,7 @@ mongoose.connect('mongodb://localhost/mongoose-bench', function (err) { --count || deferred.resolve(); } }); - if (i % 15 == 0) { + if (i % 15 === 0) { var nData = utils.clone(blogData); BlogPost.create(nData, function (err) { if (err) { @@ -420,7 +420,7 @@ mongoose.connect('mongodb://localhost/mongoose-bench', function (err) { --count || deferred.resolve(); } }); - if (i % 15 == 0) { + if (i % 15 === 0) { var nData = utils.clone(blogData); blogpost.insert(nData, function (err) { if (err) { diff --git a/bin/mongoose.debug.js b/bin/mongoose.debug.js index c7d0253b309..0db5f07b756 100644 --- a/bin/mongoose.debug.js +++ b/bin/mongoose.debug.js @@ -263,7 +263,7 @@ var cast = module.exports = function(schema, obj) { throw new Error("Must have a string or function for $where"); } - if ('function' === type) { + if (type === 'function') { obj[path] = val.toString(); } @@ -379,7 +379,7 @@ var cast = module.exports = function(schema, obj) { } else if (val === null || val === undefined) { continue; - } else if ('Object' === val.constructor.name) { + } else if (val.constructor.name === 'Object') { any$conditionals = Object.keys(val).some(function (k) { return k.charAt(0) === '$' && k !== '$id' && k !== '$ref'; @@ -577,7 +577,7 @@ Document.prototype.$__buildDoc = function (obj, fields, skipId) { // determine if this doc is a result of a query with // excluded fields - if (fields && 'Object' === utils.getFunctionName(fields.constructor)) { + if (fields && utils.getFunctionName(fields.constructor) === 'Object') { keys = Object.keys(fields); ki = keys.length; @@ -895,7 +895,7 @@ Document.prototype.set = function (path, val, type, options) { ) { this.set(path[key], prefix + key, constructing); } else if (strict) { - if ('real' === pathtype || 'virtual' === pathtype) { + if ('real' === pathtype || pathtype === 'virtual') { this.set(prefix + key, path[key], constructing); } else if ('throw' == strict) { throw new Error("Field `" + key + "` is not in schema."); @@ -1088,7 +1088,7 @@ Document.prototype.$__set = function ( if (last) { obj[parts[i]] = val; } else { - if (obj[parts[i]] && 'Object' === utils.getFunctionName(obj[parts[i]].constructor)) { + if (obj[parts[i]] && utils.getFunctionName(obj[parts[i]].constructor) === 'Object') { obj = obj[parts[i]]; } else if (obj[parts[i]] && obj[parts[i]] instanceof Embedded) { obj = obj[parts[i]]; @@ -1658,7 +1658,7 @@ function compile (tree, proto, prefix) { limb = tree[key]; define(key - , (('Object' === utils.getFunctionName(limb.constructor) + , ((utils.getFunctionName(limb.constructor === 'Object') && Object.keys(limb).length) && (!limb.type || limb.type.type) ? limb @@ -4204,7 +4204,7 @@ function SchemaArray (key, cast, options) { if (cast) { var castOptions = {}; - if ('Object' === utils.getFunctionName(cast.constructor)) { + if (utils.getFunctionName(cast.constructor) === 'Object') { if (cast.type) { // support { type: Woot } castOptions = utils.clone(cast); // do not alter user arguments @@ -4307,7 +4307,7 @@ SchemaArray.prototype.cast = function (value, doc, init) { for (var i = 0, l = indexes.length; i < l; ++i) { var pathIndex = indexes[i][0][this.path]; - if ('2dsphere' === pathIndex || '2d' === pathIndex) { + if ('2dsphere' === pathIndex || pathIndex === '2d') { return; } } @@ -4602,9 +4602,9 @@ SchemaBoolean.prototype.checkRequired = function (value) { SchemaBoolean.prototype.cast = function (value) { if (null === value) return value; - if ('0' === value) return false; - if ('true' === value) return true; - if ('false' === value) return false; + if (value === '0') return false; + if (value === 'true') return true; + if (value === 'false') return false; return !! value; } @@ -6647,7 +6647,7 @@ SchemaType.prototype.get = function (fn) { */ SchemaType.prototype.validate = function (obj, message, type) { - if ('function' == typeof obj || obj && 'RegExp' === utils.getFunctionName(obj.constructor)) { + if ('function' == typeof obj || obj && utils.getFunctionName(obj.constructor) === 'RegExp') { var properties; if (message instanceof Object && !type) { properties = utils.clone(message); @@ -6670,7 +6670,7 @@ SchemaType.prototype.validate = function (obj, message, type) { for (i=0, length=arguments.length; i' + type + ''; } return '' + type + ''; diff --git a/docs/includes/googleanalytics.jade b/docs/includes/googleanalytics.jade index aaafe24e32d..f589283902c 100644 --- a/docs/includes/googleanalytics.jade +++ b/docs/includes/googleanalytics.jade @@ -5,6 +5,6 @@ script. (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; - ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; + ga.src = ('https:' === document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); diff --git a/docs/includes/googlesearch.jade b/docs/includes/googlesearch.jade index 3a285f28c8e..04596e9cfd2 100644 --- a/docs/includes/googlesearch.jade +++ b/docs/includes/googlesearch.jade @@ -4,7 +4,7 @@ script var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true; - gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + + gcse.src = (document.location.protocol === 'https:' ? 'https:' : 'http:') + '//www.google.com/cse/cse.js?cx=' + cx; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s); diff --git a/docs/source/api.js b/docs/source/api.js index f1e01d1dcb9..998a59cf77f 100644 --- a/docs/source/api.js +++ b/docs/source/api.js @@ -147,7 +147,7 @@ function parse (docs) { // add constructor to properties too methods.some(function (method) { - if (method.ctx && 'method' == method.ctx.type && method.ctx.hasOwnProperty('constructor')) { + if (method.ctx && 'method' === method.ctx.type && method.ctx.hasOwnProperty('constructor')) { props.forEach(function (prop) { prop.ctx.constructor = method.ctx.constructor; }); @@ -201,7 +201,7 @@ function fix (str) { // parse out the ```language var code = /^(?:`{3}([^\n]+)\n)?([\s\S]*)/gm.exec($2); - if ('js' == code[1] || !code[1]) { + if ('js' === code[1] || !code[1]) { code[1] = 'javascript'; } @@ -226,9 +226,9 @@ function order (docs) { for (var i = 0; i < docs.length; ++i) { var doc = docs[i]; - if ('index.js' == doc.title) { + if ('index.js' === doc.title) { docs.unshift(docs.splice(i, 1)[0]); - } else if ('collection.js' == doc.title) { + } else if ('collection.js' === doc.title) { docs.push(docs.splice(i, 1)[0]); } diff --git a/examples/schema/schema.js b/examples/schema/schema.js index 66ce872cd7c..489dcaaea3d 100644 --- a/examples/schema/schema.js +++ b/examples/schema/schema.js @@ -64,7 +64,7 @@ BlogPost.path('date') return new Date(); }) .set(function (v) { - return v == 'now' ? new Date() : v; + return v === 'now' ? new Date() : v; }); /** diff --git a/index.html b/index.html index eeb3de3af24..a7b481e8bcb 100644 --- a/index.html +++ b/index.html @@ -14,6 +14,6 @@ (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; - ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; + ga.src = ('https:' === document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); diff --git a/lib/ES6Promise.js b/lib/ES6Promise.js index 4c112386285..a513d95e27b 100644 --- a/lib/ES6Promise.js +++ b/lib/ES6Promise.js @@ -18,7 +18,7 @@ */ function ES6Promise(fn) { - throw 'Can\'t use ES6 promise with mpromise style constructor'; + throw new Error('Can\'t use ES6 promise with mpromise style constructor'); } ES6Promise.use = function (Promise) { diff --git a/lib/aggregate.js b/lib/aggregate.js index fa38b377805..753f0b7b32a 100644 --- a/lib/aggregate.js +++ b/lib/aggregate.js @@ -131,14 +131,14 @@ Aggregate.prototype.append = function () { Aggregate.prototype.project = function (arg) { var fields = {}; - if ('object' === typeof arg && !util.isArray(arg)) { + if (typeof arg === 'object' && !util.isArray(arg)) { Object.keys(arg).forEach(function (field) { fields[field] = arg[field]; }); - } else if (1 === arguments.length && 'string' === typeof arg) { + } else if (1 === arguments.length && typeof arg === 'string') { arg.split(/\s+/).forEach(function (field) { if (!field) return; - var include = '-' == field[0] ? 0 : 1; + var include = '-' === field[0] ? 0 : 1; if (include === 0) field = field.substring(1); fields[field] = include; }); @@ -337,15 +337,15 @@ Aggregate.prototype.sort = function (arg) { var sort = {}; - if ('Object' === arg.constructor.name) { + if (arg.constructor.name === 'Object') { var desc = ['desc', 'descending', -1]; Object.keys(arg).forEach(function (field) { sort[field] = desc.indexOf(arg[field]) === -1 ? 1 : -1; }); - } else if (1 === arguments.length && 'string' == typeof arg) { + } else if (1 === arguments.length && typeof arg === 'string') { arg.split(/\s+/).forEach(function (field) { if (!field) return; - var ascend = '-' == field[0] ? -1 : 1; + var ascend = '-' === field[0] ? -1 : 1; if (ascend === -1) field = field.substring(1); sort[field] = ascend; }); @@ -555,7 +555,7 @@ Aggregate.prototype.exec = function (callback) { function isOperator(obj) { var k; - if ('object' !== typeof obj) { + if (typeof obj !== 'object') { return false; } diff --git a/lib/browserDocument.js b/lib/browserDocument.js index 196b31eb6c5..6c87d199629 100644 --- a/lib/browserDocument.js +++ b/lib/browserDocument.js @@ -58,7 +58,7 @@ function Document(obj, schema, fields, skipId, skipInit) { // var schema = this.schema; - if ('boolean' === typeof fields) { + if (typeof fields === 'boolean') { this.$__.strictMode = fields; fields = undefined; } else { diff --git a/lib/cast.js b/lib/cast.js index 57b52226569..728638ee246 100644 --- a/lib/cast.js +++ b/lib/cast.js @@ -40,7 +40,7 @@ var cast = module.exports = function (schema, obj) { throw new Error('Must have a string or function for $where'); } - if ('function' === type) { + if (type === 'function') { obj[path] = val.toString(); } @@ -104,7 +104,7 @@ var cast = module.exports = function (schema, obj) { val.$maxDistance = numbertype.castForQuery(val.$maxDistance); } - if ('$within' == geo) { + if ('$within' === geo) { var withinType = value.$center || value.$centerSphere || value.$box @@ -115,12 +115,12 @@ var cast = module.exports = function (schema, obj) { } value = withinType; - } else if ('$near' == geo && - 'string' == typeof value.type && Array.isArray(value.coordinates)) { + } else if ('$near' === geo && + typeof value.type === 'string' && Array.isArray(value.coordinates)) { // geojson; cast the coordinates value = value.coordinates; - } else if (('$near' == geo || '$nearSphere' == geo || '$geoIntersects' == geo) && - value.$geometry && 'string' == typeof value.$geometry.type && + } else if (('$near' === geo || '$nearSphere' === geo || '$geoIntersects' === geo) && + value.$geometry && typeof value.$geometry.type === 'string' && Array.isArray(value.$geometry.coordinates)) { // geojson; cast the coordinates value = value.$geometry.coordinates; @@ -153,7 +153,7 @@ var cast = module.exports = function (schema, obj) { } else if (val === null || val === undefined) { obj[path] = null; continue; - } else if ('Object' === val.constructor.name) { + } else if (val.constructor.name === 'Object') { any$conditionals = Object.keys(val).some(function (k) { return k.charAt(0) === '$' && k !== '$id' && k !== '$ref'; }); @@ -171,14 +171,14 @@ var cast = module.exports = function (schema, obj) { nested = val[$cond]; if ('$exists' === $cond) { - if ('boolean' !== typeof nested) { + if (typeof nested !== 'boolean') { throw new Error('$exists parameter must be Boolean'); } continue; } if ('$type' === $cond) { - if ('number' !== typeof nested) { + if (typeof nested !== 'number') { throw new Error('$type parameter must be Number'); } continue; diff --git a/lib/collection.js b/lib/collection.js index 2d30673e64f..f44d211adc6 100644 --- a/lib/collection.js +++ b/lib/collection.js @@ -25,7 +25,7 @@ function Collection(name, conn, opts) { ? true : opts.bufferCommands; - if ('number' == typeof opts.capped) { + if (typeof opts.capped === 'number') { opts.capped = {size: opts.capped}; } @@ -37,7 +37,7 @@ function Collection(name, conn, opts) { this.buffer = this.opts.bufferCommands; this.emitter = new EventEmitter(); - if (STATES.connected == this.conn.readyState) { + if (STATES.connected === this.conn.readyState) { this.onOpen(); } } @@ -76,9 +76,8 @@ Collection.prototype.conn; */ Collection.prototype.onOpen = function () { - var self = this; this.buffer = false; - self.doQueue(); + this.doQueue(); }; /** diff --git a/lib/connection.js b/lib/connection.js index d1df9202f2f..cda8429bbe3 100644 --- a/lib/connection.js +++ b/lib/connection.js @@ -176,7 +176,7 @@ Connection.prototype.config; Connection.prototype.open = function (host, database, port, options, callback) { var parsed; - if ('string' === typeof database) { + if (typeof database === 'string') { switch (arguments.length) { case 2: port = 27017; @@ -184,22 +184,26 @@ Connection.prototype.open = function (host, database, port, options, callback) { case 3: switch (typeof port) { case 'function': - callback = port, port = 27017; + callback = port; + port = 27017; break; case 'object': - options = port, port = 27017; + options = port; + port = 27017; break; } break; case 4: - if ('function' === typeof options) { - callback = options, options = {}; + if (typeof options === 'function') { + callback = options; + options = {}; } } } else { switch (typeof database) { case 'function': - callback = database, database = undefined; + callback = database; + database = undefined; break; case 'object': options = database; @@ -272,10 +276,10 @@ Connection.prototype.open = function (host, database, port, options, callback) { this.host = host; this.port = port; - var self = this; + var _this = this; var Promise = PromiseProvider.get(); return new Promise.ES6(function (resolve, reject) { - self._open(!!callback, function (error) { + _this._open(!!callback, function (error) { callback && callback(error); if (error) { reject(error); @@ -348,7 +352,7 @@ Connection.prototype.openSet = function (uris, database, options, callback) { break; } - if ('function' === typeof options) { + if (typeof options === 'function') { callback = options; options = {}; } @@ -359,10 +363,12 @@ Connection.prototype.openSet = function (uris, database, options, callback) { this.name = database; break; case 'function': - callback = database, database = null; + callback = database; + database = null; break; case 'object': - options = database, database = null; + options = database; + database = null; break; } } @@ -404,10 +410,10 @@ Connection.prototype.openSet = function (uris, database, options, callback) { this.config.autoIndex = options.config.autoIndex !== false; } - var self = this; + var _this = this; var Promise = PromiseProvider.get(); return new Promise.ES6(function (resolve, reject) { - self._open(!!callback, function (error) { + _this._open(!!callback, function (error) { callback && callback(error); if (error) { reject(error); @@ -445,7 +451,7 @@ Connection.prototype._open = function (emit, callback) { this.readyState = STATES.connecting; this._closeCalled = false; - var self = this; + var _this = this; var method = this.replica ? 'doOpenSet' @@ -454,16 +460,16 @@ Connection.prototype._open = function (emit, callback) { // open connection this[method](function (err) { if (err) { - self.readyState = STATES.disconnected; - if (self._hasOpened) { + _this.readyState = STATES.disconnected; + if (_this._hasOpened) { if (callback) callback(err); } else { - self.error(err, emit && callback); + _this.error(err, emit && callback); } return; } - self.onOpen(callback); + _this.onOpen(callback); }); }; @@ -474,36 +480,36 @@ Connection.prototype._open = function (emit, callback) { */ Connection.prototype.onOpen = function (callback) { - var self = this; + var _this = this; function open(err, isAuth) { if (err) { - self.readyState = isAuth ? STATES.unauthorized : STATES.disconnected; - if (self._hasOpened) { + _this.readyState = isAuth ? STATES.unauthorized : STATES.disconnected; + if (_this._hasOpened) { if (callback) { callback(err); } } else { - self.error(err, callback); + _this.error(err, callback); } return; } - self.readyState = STATES.connected; + _this.readyState = STATES.connected; // avoid having the collection subscribe to our event emitter // to prevent 0.3 warning - for (var i in self.collections) { - self.collections[i].onOpen(); + for (var i in _this.collections) { + _this.collections[i].onOpen(); } callback && callback(); - self.emit('open'); + _this.emit('open'); } // re-authenticate if (this.shouldAuthenticate()) { - self.db.authenticate(self.user, self.pass, self.options.auth, function (err) { + _this.db.authenticate(_this.user, _this.pass, _this.options.auth, function (err) { open(err, true); }); } else { @@ -520,10 +526,10 @@ Connection.prototype.onOpen = function (callback) { */ Connection.prototype.close = function (callback) { - var self = this; + var _this = this; var Promise = PromiseProvider.get(); return new Promise.ES6(function (resolve, reject) { - self._close(function (error) { + _this._close(function (error) { callback && callback(error); if (error) { reject(error); @@ -541,7 +547,7 @@ Connection.prototype.close = function (callback) { * @api private */ Connection.prototype._close = function (callback) { - var self = this; + var _this = this; this._closeCalled = true; switch (this.readyState) { @@ -554,9 +560,9 @@ Connection.prototype._close = function (callback) { this.readyState = STATES.disconnecting; this.doClose(function (err) { if (err) { - self.error(err, callback); + _this.error(err, callback); } else { - self.onClose(); + _this.onClose(); callback && callback(); } }); @@ -564,7 +570,7 @@ Connection.prototype._close = function (callback) { case 2: // connecting this.once('open', function () { - self.close(callback); + _this.close(callback); }); break; @@ -649,7 +655,7 @@ Connection.prototype.collection = function (name, options) { Connection.prototype.model = function (name, schema, collection) { // collection name discovery - if ('string' == typeof schema) { + if (typeof schema === 'string') { collection = schema; schema = false; } @@ -660,7 +666,7 @@ Connection.prototype.model = function (name, schema, collection) { if (this.models[name] && !collection) { // model exists but we are not subclassing with custom collection - if (schema && schema.instanceOfSchema && schema != this.models[name].schema) { + if (schema && schema.instanceOfSchema && schema !== this.models[name].schema) { throw new MongooseError.OverwriteModelError(name); } return this.models[name]; @@ -699,8 +705,8 @@ Connection.prototype.model = function (name, schema, collection) { throw new MongooseError.MissingSchemaError(name); } - if (this == model.prototype.db - && (!collection || collection == model.collection.name)) { + if (this === model.prototype.db + && (!collection || collection === model.collection.name)) { // model already uses this connection. // only the first model with this name is cached to allow diff --git a/lib/document.js b/lib/document.js index aa51044ed02..bc955920dbc 100644 --- a/lib/document.js +++ b/lib/document.js @@ -44,7 +44,7 @@ function Document(obj, fields, skipId) { var schema = this.schema; - if ('boolean' === typeof fields) { + if (typeof fields === 'boolean') { this.$__.strictMode = fields; fields = undefined; } else { @@ -65,12 +65,12 @@ function Document(obj, fields, skipId) { } if (!schema.options.strict && obj) { - var self = this, + var _this = this, keys = Object.keys(this._doc); keys.forEach(function (key) { if (!(key in schema.tree)) { - defineKey(key, null, self); + defineKey(key, null, _this); } }); } @@ -153,7 +153,7 @@ Document.prototype.$__buildDoc = function (obj, fields, skipId) { var exclude = null; var keys; var ki; - var self = this; + var _this = this; // determine if this doc is a result of a query with // excluded fields @@ -181,7 +181,7 @@ Document.prototype.$__buildDoc = function (obj, fields, skipId) { for (; ii < plen; ++ii) { var p = paths[ii]; - if ('_id' == p) { + if (p === '_id') { if (skipId) { continue; } @@ -222,24 +222,24 @@ Document.prototype.$__buildDoc = function (obj, fields, skipId) { continue; } - def = type.getDefault(self, true); - if ('undefined' !== typeof def) { + def = type.getDefault(_this, true); + if (typeof def !== 'undefined') { doc_[piece] = def; - self.$__.activePaths.default(p); + _this.$__.activePaths.default(p); } } else if (included) { // selected field - def = type.getDefault(self, true); - if ('undefined' !== typeof def) { + def = type.getDefault(_this, true); + if (typeof def !== 'undefined') { doc_[piece] = def; - self.$__.activePaths.default(p); + _this.$__.activePaths.default(p); } } } else { - def = type.getDefault(self, true); - if ('undefined' !== typeof def) { + def = type.getDefault(_this, true); + if (typeof def !== 'undefined') { doc_[piece] = def; - self.$__.activePaths.default(p); + _this.$__.activePaths.default(p); } } } else { @@ -266,7 +266,7 @@ Document.prototype.init = function (doc, opts, fn) { // do not prefix this method with $__ since its // used by public hooks - if ('function' == typeof opts) { + if (typeof opts === 'function') { fn = opts; opts = null; } @@ -275,7 +275,7 @@ Document.prototype.init = function (doc, opts, fn) { // handle docs with populated paths // If doc._id is not null or undefined - if (doc._id != null && opts && opts.populated && opts.populated.length) { + if (doc._id !== null && opts && opts.populated && opts.populated.length) { var id = String(doc._id); for (var i = 0; i < opts.populated.length; ++i) { var item = opts.populated[i]; @@ -317,7 +317,7 @@ function init(self, obj, doc, prefix) { schema = self.schema.path(path); if (!schema && utils.isObject(obj[i]) && - (!obj[i].constructor || 'Object' == utils.getFunctionName(obj[i].constructor))) { + (!obj[i].constructor || 'Object' === utils.getFunctionName(obj[i].constructor))) { // assume nested object if (!doc[i]) { doc[i] = {}; @@ -365,7 +365,7 @@ function init(self, obj, doc, prefix) { Document.prototype.$__storeShard = function () { // backwards compat var key = this.schema.options.shardKey || this.schema.options.shardkey; - if (!(key && 'Object' == utils.getFunctionName(key.constructor))) { + if (!(key && 'Object' === utils.getFunctionName(key.constructor))) { return; } @@ -378,7 +378,7 @@ Document.prototype.$__storeShard = function () { val = this.getValue(paths[i]); if (isMongooseObject(val)) { orig[paths[i]] = val.toObject({depopulate: true}); - } else if (null != val && + } else if (null !== val && val.valueOf && // Explicitly don't take value of dates (!val.constructor || utils.getFunctionName(val.constructor) !== 'Date')) { @@ -455,7 +455,7 @@ Document.prototype.update = function update() { */ Document.prototype.set = function (path, val, type, options) { - if (type && 'Object' == utils.getFunctionName(type.constructor)) { + if (type && 'Object' === utils.getFunctionName(type.constructor)) { options = type; type = undefined; } @@ -504,10 +504,10 @@ Document.prototype.set = function (path, val, type, options) { var pathName = prefix + key; pathtype = this.schema.pathType(pathName); - if (null != path[key] + if (null !== path[key] // need to know if plain object - no Buffer, ObjectId, ref, etc && utils.isObject(path[key]) - && (!path[key].constructor || 'Object' == utils.getFunctionName(path[key].constructor)) + && (!path[key].constructor || 'Object' === utils.getFunctionName(path[key].constructor)) && 'virtual' !== pathtype && 'real' !== pathtype && !(this.$__path(pathName) instanceof MixedSchema) @@ -516,7 +516,7 @@ Document.prototype.set = function (path, val, type, options) { this.schema.paths[pathName].options.ref)) { this.set(path[key], prefix + key, constructing); } else if (strict) { - if ('real' === pathtype || 'virtual' === pathtype) { + if ('real' === pathtype || pathtype === 'virtual') { // Check for setting single embedded schema to document (gh-3535) if (this.schema.paths[pathName] && this.schema.paths[pathName].$isSingleNested && @@ -527,7 +527,7 @@ Document.prototype.set = function (path, val, type, options) { } else if (pathtype === 'nested' && path[key] instanceof Document) { this.set(prefix + key, path[key].toObject({virtuals: false}), constructing); - } else if ('throw' == strict) { + } else if (strict === 'throw') { if (pathtype === 'nested') { throw new ObjectExpectedError(key, path[key]); } else { @@ -547,9 +547,9 @@ Document.prototype.set = function (path, val, type, options) { // docschema = new Schema({ path: { nest: 'string' }}) // doc.set('path', obj); var pathType = this.schema.pathType(path); - if ('nested' == pathType && val) { + if ('nested' === pathType && val) { if (utils.isObject(val) && - (!val.constructor || 'Object' == utils.getFunctionName(val.constructor))) { + (!val.constructor || 'Object' === utils.getFunctionName(val.constructor))) { if (!merge) { this.setValue(path, null); } @@ -563,7 +563,7 @@ Document.prototype.set = function (path, val, type, options) { var schema; var parts = path.split('.'); - if ('adhocOrUndefined' == pathType && strict) { + if ('adhocOrUndefined' === pathType && strict) { // check for roots that are Mixed types var mixed; @@ -578,12 +578,12 @@ Document.prototype.set = function (path, val, type, options) { } if (!mixed) { - if ('throw' == strict) { + if (strict === 'throw') { throw new StrictModeError(path); } return this; } - } else if ('virtual' == pathType) { + } else if (pathType === 'virtual') { schema = this.schema.virtualpath(path); schema.applySetters(val, this); return this; @@ -719,7 +719,7 @@ Document.prototype.$__shouldModify = function (pathToMark, path, constructing, p } if (!constructing && - null != val && + null !== val && path in this.$__.activePaths.states.default && deepEqual(val, schema.getDefault(this, constructing))) { // a path with a default was $unset on the server @@ -1001,7 +1001,7 @@ Document.prototype.isInit = function (path) { Document.prototype.isSelected = function isSelected(path) { if (this.$__.selected) { - if ('_id' === path) { + if (path === '_id') { return 0 !== this.$__.selected._id; } @@ -1017,7 +1017,7 @@ Document.prototype.isSelected = function isSelected(path) { while (i--) { cur = paths[i]; - if ('_id' == cur) { + if (cur === '_id') { continue; } inclusive = !!this.$__.selected[cur]; @@ -1033,7 +1033,7 @@ Document.prototype.isSelected = function isSelected(path) { while (i--) { cur = paths[i]; - if ('_id' == cur) { + if (cur === '_id') { continue; } @@ -1222,7 +1222,7 @@ Document.prototype.$__validate = function (callback) { */ Document.prototype.validateSync = function (pathsToValidate) { - var self = this; + var _this = this; if (typeof pathsToValidate === 'string') { pathsToValidate = pathsToValidate.split(' '); @@ -1230,7 +1230,7 @@ Document.prototype.validateSync = function (pathsToValidate) { // only validate required fields when necessary var paths = Object.keys(this.$__.activePaths.states.require).filter(function (path) { - if (!self.isSelected(path) && !self.isModified(path)) { + if (!_this.isSelected(path) && !_this.isModified(path)) { return false; } return true; @@ -1259,30 +1259,30 @@ Document.prototype.validateSync = function (pathsToValidate) { validating[path] = true; - var p = self.schema.path(path); + var p = _this.schema.path(path); if (!p) { return; } - if (!self.$isValid(path)) { + if (!_this.$isValid(path)) { return; } - var val = self.getValue(path); - var err = p.doValidateSync(val, self); + var val = _this.getValue(path); + var err = p.doValidateSync(val, _this); if (err) { - self.invalidate(path, err, undefined, true); + _this.invalidate(path, err, undefined, true); } }); - var err = self.$__.validationError; - self.$__.validationError = undefined; - self.emit('validate', self); + var err = _this.$__.validationError; + _this.$__.validationError = undefined; + _this.emit('validate', _this); if (err) { for (var key in err.errors) { // Make sure cast errors persist if (err.errors[key] instanceof MongooseError.CastError) { - self.invalidate(key, err.errors[key]); + _this.invalidate(key, err.errors[key]); } } } @@ -1328,7 +1328,7 @@ Document.prototype.invalidate = function (path, err, val) { return; } - if (!err || 'string' === typeof err) { + if (!err || typeof err === 'string') { err = new ValidatorError({ path: path, message: err, @@ -1337,7 +1337,7 @@ Document.prototype.invalidate = function (path, err, val) { }); } - if (this.$__.validationError == err) { + if (this.$__.validationError === err) { return; } @@ -1387,12 +1387,12 @@ Document.prototype.$isValid = function (path) { */ Document.prototype.$__reset = function reset() { - var self = this; + var _this = this; DocumentArray || (DocumentArray = require('./types/documentarray')); this.$__.activePaths .map('init', 'modify', function (i) { - return self.getValue(i); + return _this.getValue(i); }) .filter(function (val) { return val && val instanceof Array && val.isMongooseDocumentArray && val.length; @@ -1421,9 +1421,9 @@ Document.prototype.$__reset = function reset() { this.$__.activePaths.clear('default'); this.$__.validationError = undefined; this.errors = undefined; - self = this; + _this = this; this.schema.requiredPaths().forEach(function (path) { - self.$__.activePaths.require(path); + _this.$__.activePaths.require(path); }); return this; @@ -1438,26 +1438,26 @@ Document.prototype.$__reset = function reset() { */ Document.prototype.$__dirty = function () { - var self = this; + var _this = this; var all = this.$__.activePaths.map('modify', function (path) { return { path: path, - value: self.getValue(path), - schema: self.$__path(path) + value: _this.getValue(path), + schema: _this.$__path(path) }; }); // gh-2558: if we had to set a default and the value is not undefined, // we have to save as well all = all.concat(this.$__.activePaths.map('default', function (path) { - if (path === '_id' || !self.getValue(path)) { + if (path === '_id' || !_this.getValue(path)) { return; } return { path: path, - value: self.getValue(path), - schema: self.$__path(path) + value: _this.getValue(path), + schema: _this.$__path(path) }; })); @@ -1548,7 +1548,7 @@ function defineKey(prop, subprops, prototype, prefix, keys, options) { enumerable: true, configurable: true, get: function () { - var _self = this; + var _this = this; if (!this.$__.getters) { this.$__.getters = {}; } @@ -1581,7 +1581,7 @@ function defineKey(prop, subprops, prototype, prefix, keys, options) { configurable: true, writable: false, value: function () { - return _self.get(path); + return _this.get(path); } }); @@ -1590,7 +1590,7 @@ function defineKey(prop, subprops, prototype, prefix, keys, options) { configurable: true, writable: false, value: function () { - return _self.get(path); + return _this.get(path); } }); @@ -1728,16 +1728,16 @@ Document.prototype.$__registerHooksFromSchema = function () { Embedded = Embedded || require('./types/embedded'); var Promise = PromiseProvider.get(); - var self = this; - var q = self.schema && self.schema.callQueue; + var _this = this; + var q = _this.schema && _this.schema.callQueue; if (!q.length) { - return self; + return _this; } // we are only interested in 'pre' hooks, and group by point-cut var toWrap = q.reduce(function (seed, pair) { if (pair[0] !== 'pre' && pair[0] !== 'post' && pair[0] !== 'on') { - self[pair[0]].apply(self, pair[1]); + _this[pair[0]].apply(_this, pair[1]); return seed; } var args = [].slice.call(pair[1]); @@ -1757,20 +1757,20 @@ Document.prototype.$__registerHooksFromSchema = function () { // 'post' hooks are simpler toWrap.post.forEach(function (args) { - self.on.apply(self, args); + _this.on.apply(_this, args); }); delete toWrap.post; // 'init' should be synchronous on subdocuments - if (toWrap.init && self instanceof Embedded) { + if (toWrap.init && _this instanceof Embedded) { if (toWrap.init.pre) { toWrap.init.pre.forEach(function (args) { - self.pre.apply(self, args); + _this.pre.apply(_this, args); }); } if (toWrap.init.post) { toWrap.init.post.forEach(function (args) { - self.post.apply(self, args); + _this.post.apply(_this, args); }); } delete toWrap.init; @@ -1778,12 +1778,12 @@ Document.prototype.$__registerHooksFromSchema = function () { // Set hooks also need to be sync re: gh-3479 if (toWrap.set.pre) { toWrap.set.pre.forEach(function (args) { - self.pre.apply(self, args); + _this.pre.apply(_this, args); }); } if (toWrap.set.post) { toWrap.set.post.forEach(function (args) { - self.post.apply(self, args); + _this.post.apply(_this, args); }); } delete toWrap.set; @@ -1792,11 +1792,11 @@ Document.prototype.$__registerHooksFromSchema = function () { Object.keys(toWrap).forEach(function (pointCut) { // this is so we can wrap everything into a promise; var newName = ('$__original_' + pointCut); - if (!self[pointCut]) { + if (!_this[pointCut]) { return; } - self[newName] = self[pointCut]; - self[pointCut] = function wrappedPointCut() { + _this[newName] = _this[pointCut]; + _this[pointCut] = function wrappedPointCut() { var args = [].slice.call(arguments); var lastArg = args.pop(); var fn; @@ -1809,7 +1809,7 @@ Document.prototype.$__registerHooksFromSchema = function () { } args.push(function (error, result) { if (error) { - self.$__handleReject(error); + _this.$__handleReject(error); fn && fn(error); reject(error); return; @@ -1819,20 +1819,20 @@ Document.prototype.$__registerHooksFromSchema = function () { resolve(result); }); - self[newName].apply(self, args); + _this[newName].apply(_this, args); }); }; toWrap[pointCut].pre.forEach(function (args) { args[0] = newName; - self.pre.apply(self, args); + _this.pre.apply(_this, args); }); toWrap[pointCut].post.forEach(function (args) { args[0] = newName; - self.post.apply(self, args); + _this.post.apply(_this, args); }); }); - return self; + return _this; }; Document.prototype.$__handleReject = function handleReject(err) { @@ -1870,7 +1870,7 @@ Document.prototype.$toObject = function (options, json) { // When internally saving this document we always pass options, // bypassing the custom schema options. - if (!(options && 'Object' == utils.getFunctionName(options.constructor)) || + if (!(options && 'Object' === utils.getFunctionName(options.constructor)) || (options && options._useSchemaOptions)) { if (json) { options = this.schema.options.toJSON ? @@ -1936,9 +1936,9 @@ Document.prototype.$toObject = function (options, json) { options.transform = originalTransform; } - if ('function' == typeof transform) { + if (typeof transform === 'function') { var xformed = transform(this, ret, options); - if ('undefined' != typeof xformed) { + if ('undefined' !== typeof xformed) { ret = xformed; } } @@ -2163,7 +2163,7 @@ Document.prototype.toJSON = function (options) { */ Document.prototype.inspect = function (options) { - var opts = options && 'Object' == utils.getFunctionName(options.constructor) ? options : {}; + var opts = options && 'Object' === utils.getFunctionName(options.constructor) ? options : {}; opts.minimize = false; opts.retainKeyOrder = true; return this.toObject(opts); @@ -2217,7 +2217,7 @@ Document.prototype.equals = function (doc) { * model: 'modelName' * options: opts * }, function (err, user) { - * assert(doc._id == user._id) // the document itself is passed + * assert(doc._id === user._id) // the document itself is passed * }) * * // summary @@ -2334,7 +2334,7 @@ Document.prototype.execPopulate = function () { Document.prototype.populated = function (path, val, options) { // val and options are internal - if (val == null) { + if (val === null || val === void 0) { if (!this.$__.populated) { return undefined; } diff --git a/lib/drivers/node-mongodb-native/collection.js b/lib/drivers/node-mongodb-native/collection.js index 6dcc39f1d28..b6b5f65f3c7 100644 --- a/lib/drivers/node-mongodb-native/collection.js +++ b/lib/drivers/node-mongodb-native/collection.js @@ -34,22 +34,22 @@ NativeCollection.prototype.__proto__ = MongooseCollection.prototype; */ NativeCollection.prototype.onOpen = function () { - var self = this; + var _this = this; // always get a new collection in case the user changed host:port // of parent db instance when re-opening the connection. - if (!self.opts.capped.size) { + if (!_this.opts.capped.size) { // non-capped - return self.conn.db.collection(self.name, callback); + return _this.conn.db.collection(_this.name, callback); } // capped - return self.conn.db.collection(self.name, function (err, c) { + return _this.conn.db.collection(_this.name, function (err, c) { if (err) return callback(err); // discover if this collection exists and if it is capped - self.conn.db.listCollections({name: self.name}).toArray(function (err, docs) { + _this.conn.db.listCollections({name: _this.name}).toArray(function (err, docs) { if (err) { return callback(err); } @@ -60,7 +60,7 @@ NativeCollection.prototype.onOpen = function () { if (doc.options && doc.options.capped) { callback(null, c); } else { - var msg = 'A non-capped collection exists with the name: ' + self.name + '\n\n' + var msg = 'A non-capped collection exists with the name: ' + _this.name + '\n\n' + ' To use this collection as a capped collection, please ' + 'first convert it.\n' + ' http://www.mongodb.org/display/DOCS/Capped+Collections#CappedCollections-Convertingacollectiontocapped'; @@ -69,9 +69,9 @@ NativeCollection.prototype.onOpen = function () { } } else { // create - var opts = utils.clone(self.opts.capped); + var opts = utils.clone(_this.opts.capped); opts.capped = true; - self.conn.db.createCollection(self.name, opts, callback); + _this.conn.db.createCollection(_this.name, opts, callback); } }); }); @@ -79,10 +79,10 @@ NativeCollection.prototype.onOpen = function () { function callback(err, collection) { if (err) { // likely a strict mode error - self.conn.emit('error', err); + _this.conn.emit('error', err); } else { - self.collection = collection; - MongooseCollection.prototype.onOpen.call(self); + _this.collection = collection; + MongooseCollection.prototype.onOpen.call(_this); } } }; @@ -121,15 +121,15 @@ for (var i in Collection.prototype) { var collection = this.collection, args = arguments, - self = this, - debug = self.conn.base.options.debug; + _this = this, + debug = _this.conn.base.options.debug; if (debug) { - if ('function' === typeof debug) { + if (typeof debug === 'function') { debug.apply(debug - , [self.name, i].concat(utils.args(args, 0, args.length - 1))); + , [_this.name, i].concat(utils.args(args, 0, args.length - 1))); } else { - this.$print(self.name, i, args); + this.$print(_this.name, i, args); } } @@ -163,7 +163,7 @@ NativeCollection.prototype.$print = function (name, i, args) { NativeCollection.prototype.$format = function (arg) { var type = typeof arg; - if ('function' === type || 'undefined' === type) return ''; + if (type === 'function' || type === 'undefined') return ''; return format(arg); }; @@ -175,15 +175,15 @@ function format(obj, sub) { var x = utils.clone(obj, {retainKeyOrder: 1}); var representation; if (x != null) { - if ('Binary' === x.constructor.name) { + if (x.constructor.name === 'Binary') { x = '[object Buffer]'; - } else if ('ObjectID' === x.constructor.name) { + } else if (x.constructor.name === 'ObjectID') { representation = 'ObjectId("' + x.toHexString() + '")'; x = {inspect: function () { return representation; }}; - } else if ('Date' === x.constructor.name) { + } else if (x.constructor.name === 'Date') { representation = 'new Date("' + x.toUTCString() + '")'; x = {inspect: function () { return representation; }}; - } else if ('Object' === x.constructor.name) { + } else if (x.constructor.name === 'Object') { var keys = Object.keys(x); var numKeys = keys.length; var key; diff --git a/lib/drivers/node-mongodb-native/connection.js b/lib/drivers/node-mongodb-native/connection.js index 037e09b972f..c9045042a0f 100644 --- a/lib/drivers/node-mongodb-native/connection.js +++ b/lib/drivers/node-mongodb-native/connection.js @@ -53,10 +53,10 @@ NativeConnection.prototype.doOpen = function (fn) { this.db = new Db(this.name, server, this.options.db); } - var self = this; + var _this = this; this.db.open(function (err) { if (err) return fn(err); - listen(self); + listen(_this); fn(); }); @@ -99,7 +99,7 @@ NativeConnection.prototype.useDb = function (name) { // the 'open' event of the connection before doing the rest of the setup // the 'connected' event is the first time we'll have access to the db object - var self = this; + var _this = this; if (this.db && this._readyState === STATES.connected) { wireup(); @@ -108,7 +108,7 @@ NativeConnection.prototype.useDb = function (name) { } function wireup() { - newConn.db = self.db.db(name); + newConn.db = _this.db.db(name); newConn.onOpen(); // setup the events appropriately listen(newConn); @@ -180,12 +180,12 @@ function listen(conn) { NativeConnection.prototype.doOpenSet = function (fn) { var servers = [], - self = this; + _this = this; this.hosts.forEach(function (server) { var host = server.host || server.ipc; var port = server.port || 27017; - servers.push(new Server(host, port, self.options.server)); + servers.push(new Server(host, port, _this.options.server)); }); var server = this.options.mongos @@ -194,13 +194,13 @@ NativeConnection.prototype.doOpenSet = function (fn) { this.db = new Db(this.name, server, this.options.db); this.db.on('fullsetup', function () { - self.emit('fullsetup'); + _this.emit('fullsetup'); }); this.db.open(function (err) { if (err) return fn(err); fn(); - listen(self); + listen(_this); }); return this; @@ -243,55 +243,55 @@ NativeConnection.prototype.parseOptions = function (passed, connStrOpts) { switch (name) { case 'ssl': case 'poolSize': - if ('undefined' == typeof o.server[name]) { + if (typeof o.server[name] === 'undefined') { o.server[name] = o.replset[name] = opts[name]; } break; case 'slaveOk': - if ('undefined' == typeof o.server.slave_ok) { + if (typeof o.server.slave_ok === 'undefined') { o.server.slave_ok = opts[name]; } break; case 'autoReconnect': - if ('undefined' == typeof o.server.auto_reconnect) { + if (typeof o.server.auto_reconnect === 'undefined') { o.server.auto_reconnect = opts[name]; } break; case 'socketTimeoutMS': case 'connectTimeoutMS': - if ('undefined' == typeof o.server.socketOptions[name]) { + if (typeof o.server.socketOptions[name] === 'undefined') { o.server.socketOptions[name] = o.replset.socketOptions[name] = opts[name]; } break; case 'authdb': - if ('undefined' == typeof o.auth.authdb) { + if (typeof o.auth.authdb === 'undefined') { o.auth.authdb = opts[name]; } break; case 'authSource': - if ('undefined' == typeof o.auth.authSource) { + if (typeof o.auth.authSource === 'undefined') { o.auth.authSource = opts[name]; } break; case 'retries': case 'reconnectWait': case 'rs_name': - if ('undefined' == typeof o.replset[name]) { + if (typeof o.replset[name] === 'undefined') { o.replset[name] = opts[name]; } break; case 'replicaSet': - if ('undefined' == typeof o.replset.rs_name) { + if (typeof o.replset.rs_name === 'undefined') { o.replset.rs_name = opts[name]; } break; case 'readSecondary': - if ('undefined' == typeof o.replset.read_secondary) { + if (typeof o.replset.read_secondary === 'undefined') { o.replset.read_secondary = opts[name]; } break; case 'nativeParser': - if ('undefined' == typeof o.db.native_parser) { + if (typeof o.db.native_parser === 'undefined') { o.db.native_parser = opts[name]; } break; @@ -300,17 +300,17 @@ NativeConnection.prototype.parseOptions = function (passed, connStrOpts) { case 'fsync': case 'journal': case 'wtimeoutMS': - if ('undefined' == typeof o.db[name]) { + if (typeof o.db[name] === 'undefined') { o.db[name] = opts[name]; } break; case 'readPreference': - if ('undefined' == typeof o.db.readPreference) { + if (typeof o.db.readPreference === 'undefined') { o.db.readPreference = opts[name]; } break; case 'readPreferenceTags': - if ('undefined' == typeof o.db.read_preference_tags) { + if (typeof o.db.read_preference_tags === 'undefined') { o.db.read_preference_tags = opts[name]; } break; diff --git a/lib/error/validation.js b/lib/error/validation.js index 81dc219cb21..7e9d01127b4 100644 --- a/lib/error/validation.js +++ b/lib/error/validation.js @@ -1,4 +1,3 @@ - /*! * Module requirements */ @@ -48,7 +47,9 @@ ValidationError.prototype.toString = function () { var msgs = []; Object.keys(this.errors).forEach(function (key) { - if (this == this.errors[key]) return; + if (this === this.errors[key]) { + return; + } msgs.push(String(this.errors[key])); }, this); diff --git a/lib/index.js b/lib/index.js index 5554327b840..acef70a8fe3 100644 --- a/lib/index.js +++ b/lib/index.js @@ -66,7 +66,7 @@ Mongoose.prototype.STATES = STATES; */ Mongoose.prototype.set = function (key, value) { - if (arguments.length == 1) { + if (arguments.length === 1) { return this.options[key]; } @@ -312,7 +312,7 @@ Mongoose.prototype.disconnect = function (fn) { */ Mongoose.prototype.model = function (name, schema, collection, skipInit) { - if ('string' == typeof schema) { + if (typeof schema === 'string') { collection = schema; schema = false; } @@ -321,7 +321,7 @@ Mongoose.prototype.model = function (name, schema, collection, skipInit) { schema = new Schema(schema); } - if ('boolean' === typeof collection) { + if (typeof collection === 'boolean') { skipInit = collection; collection = null; } @@ -352,7 +352,7 @@ Mongoose.prototype.model = function (name, schema, collection, skipInit) { // connection.model() may be passing a different schema for // an existing model name. in this case don't read from cache. if (this.models[name] && false !== options.cache) { - if (schema && schema.instanceOfSchema && schema != this.models[name].schema) { + if (schema && schema.instanceOfSchema && schema !== this.models[name].schema) { throw new mongoose.Error.OverwriteModelError(name); } diff --git a/lib/model.js b/lib/model.js index 678b23d61ad..1d074e61a90 100644 --- a/lib/model.js +++ b/lib/model.js @@ -269,7 +269,7 @@ Model.prototype.$__save = function (options, callback) { */ Model.prototype.save = function (options, fn) { - if ('function' == typeof options) { + if (typeof options === 'function') { fn = options; options = undefined; } @@ -362,7 +362,7 @@ function operand(self, where, delta, data, val, op) { // only increment the version if an array position changes. // modifying elements of an array is ok if position does not change. - if ('$push' == op || '$pushAll' == op || '$addToSet' == op) { + if ('$push' === op || '$pushAll' === op || '$addToSet' === op) { self.$__.version = VERSION_INC; } else if (/^\$p/.test(op)) { // potentially changing array positions @@ -393,7 +393,7 @@ function handleAtomics(self, where, delta, data, value) { return; } - if ('function' == typeof value.$__getAtomics) { + if (typeof value.$__getAtomics === 'function') { value.$__getAtomics().forEach(function (atomic) { var op = atomic[0]; var val = atomic[1]; @@ -456,7 +456,7 @@ function handleAtomics(self, where, delta, data, value) { Model.prototype.$__delta = function () { var dirty = this.$__dirty(); - if (!dirty.length && VERSION_ALL != this.$__.version) return; + if (!dirty.length && VERSION_ALL !== this.$__.version) return; var where = {}, delta = {}, @@ -676,7 +676,7 @@ Model.prototype.$__where = function _where(where) { */ Model.prototype.remove = function remove(options, fn) { - if ('function' == typeof options) { + if (typeof options === 'function') { fn = options; options = undefined; } @@ -908,10 +908,10 @@ Model.init = function init() { */ Model.ensureIndexes = function ensureIndexes(cb) { - var self = this; + var _this = this; var Promise = PromiseProvider.get(); return new Promise.ES6(function (resolve, reject) { - var indexes = self.schema.indexes(); + var indexes = _this.schema.indexes(); if (!indexes.length) { process.nextTick(function () { cb && cb(); @@ -923,19 +923,19 @@ Model.ensureIndexes = function ensureIndexes(cb) { // with background indexes. var done = function (err) { - if (err && self.schema.options.emitIndexErrors) { - self.emit('error', err); + if (err && _this.schema.options.emitIndexErrors) { + _this.emit('error', err); } - self.emit('index', err); + _this.emit('index', err); cb && cb(err); err ? reject(err) : resolve(); }; var indexSingleDone = function (err, fields, options, name) { - self.emit('index-single-done', err, fields, options, name); + _this.emit('index-single-done', err, fields, options, name); }; var indexSingleStart = function (fields, options) { - self.emit('index-single-start', fields, options); + _this.emit('index-single-start', fields, options); }; var create = function () { @@ -948,7 +948,7 @@ Model.ensureIndexes = function ensureIndexes(cb) { indexSingleStart(indexFields, options); - self.collection.ensureIndex(indexFields, options, tick(function (err, name) { + _this.collection.ensureIndex(indexFields, options, tick(function (err, name) { indexSingleDone(err, indexFields, options, name); if (err) { return done(err); @@ -1053,7 +1053,7 @@ Model.discriminators; */ Model.remove = function remove(conditions, callback) { - if ('function' === typeof conditions) { + if (typeof conditions === 'function') { callback = conditions; conditions = {}; } @@ -1106,16 +1106,16 @@ Model.remove = function remove(conditions, callback) { */ Model.find = function find(conditions, projection, options, callback) { - if ('function' == typeof conditions) { + if (typeof conditions === 'function') { callback = conditions; conditions = {}; projection = null; options = null; - } else if ('function' == typeof projection) { + } else if (typeof projection === 'function') { callback = projection; projection = null; options = null; - } else if ('function' == typeof options) { + } else if (typeof options === 'function') { callback = options; options = null; } @@ -1222,14 +1222,14 @@ Model.findById = function findById(id, projection, options, callback) { */ Model.findOne = function findOne(conditions, projection, options, callback) { - if ('function' == typeof options) { + if (typeof options === 'function') { callback = options; options = null; - } else if ('function' == typeof projection) { + } else if (typeof projection === 'function') { callback = projection; projection = null; options = null; - } else if ('function' == typeof conditions) { + } else if (typeof conditions === 'function') { callback = conditions; conditions = {}; projection = null; @@ -1264,8 +1264,9 @@ Model.findOne = function findOne(conditions, projection, options, callback) { */ Model.count = function count(conditions, callback) { - if ('function' === typeof conditions) { - callback = conditions, conditions = {}; + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; } // get the mongodb collection object @@ -1302,7 +1303,7 @@ Model.distinct = function distinct(field, conditions, callback) { // get the mongodb collection object var mq = new Query({}, {}, this, this.collection); - if ('function' == typeof conditions) { + if (typeof conditions === 'function') { callback = conditions; conditions = {}; } @@ -1425,11 +1426,11 @@ Model.$where = function $where() { */ Model.findOneAndUpdate = function (conditions, update, options, callback) { - if ('function' == typeof options) { + if (typeof options === 'function') { callback = options; options = null; } else if (1 === arguments.length) { - if ('function' == typeof conditions) { + if (typeof conditions === 'function') { var msg = 'Model.findOneAndUpdate(): First argument must not be a function.\n\n' + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options, callback)\n' + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options)\n' @@ -1535,7 +1536,7 @@ Model.findOneAndUpdate = function (conditions, update, options, callback) { Model.findByIdAndUpdate = function (id, update, options, callback) { var args; if (1 === arguments.length) { - if ('function' == typeof id) { + if (typeof id === 'function') { var msg = 'Model.findByIdAndUpdate(): First argument must not be a function.\n\n' + ' ' + this.modelName + '.findByIdAndUpdate(id, callback)\n' + ' ' + this.modelName + '.findByIdAndUpdate(id)\n' @@ -1605,7 +1606,7 @@ Model.findByIdAndUpdate = function (id, update, options, callback) { */ Model.findOneAndRemove = function (conditions, options, callback) { - if (1 === arguments.length && 'function' == typeof conditions) { + if (1 === arguments.length && typeof conditions === 'function') { var msg = 'Model.findOneAndRemove(): First argument must not be a function.\n\n' + ' ' + this.modelName + '.findOneAndRemove(conditions, callback)\n' + ' ' + this.modelName + '.findOneAndRemove(conditions)\n' @@ -1613,7 +1614,7 @@ Model.findOneAndRemove = function (conditions, options, callback) { throw new TypeError(msg); } - if ('function' == typeof options) { + if (typeof options === 'function') { callback = options; options = undefined; } @@ -1659,7 +1660,7 @@ Model.findOneAndRemove = function (conditions, options, callback) { */ Model.findByIdAndRemove = function (id, options, callback) { - if (1 === arguments.length && 'function' == typeof id) { + if (1 === arguments.length && typeof id === 'function') { var msg = 'Model.findByIdAndRemove(): First argument must not be a function.\n\n' + ' ' + this.modelName + '.findByIdAndRemove(id, callback)\n' + ' ' + this.modelName + '.findByIdAndRemove(id)\n' @@ -1712,7 +1713,7 @@ Model.create = function create(doc, callback) { cb = callback; } else { var last = arguments[arguments.length - 1]; - if ('function' == typeof last) { + if (typeof last === 'function') { cb = last; args = utils.args(arguments, 0, arguments.length - 1); } else { @@ -1721,7 +1722,7 @@ Model.create = function create(doc, callback) { } var Promise = PromiseProvider.get(); - var ModelConstructor = this; + var _this = this; var promise = new Promise.ES6(function (resolve, reject) { if (args.length === 0) { @@ -1735,7 +1736,7 @@ Model.create = function create(doc, callback) { var toExecute = []; args.forEach(function (doc) { toExecute.push(function (callback) { - var toSave = new ModelConstructor(doc); + var toSave = new _this(doc); var callbackWrapper = function (error, doc) { if (error) { return callback(error); @@ -1762,12 +1763,12 @@ Model.create = function create(doc, callback) { if (doc instanceof Array) { resolve(savedDocs); - cb && cb.call(ModelConstructor, null, savedDocs); + cb && cb.call(_this, null, savedDocs); } else { resolve.apply(promise, savedDocs); if (cb) { savedDocs.unshift(null); - cb.apply(ModelConstructor, savedDocs); + cb.apply(_this, savedDocs); } } }); @@ -2015,7 +2016,7 @@ Model.update = function update(conditions, doc, options, callback) { */ Model.mapReduce = function mapReduce(o, callback) { - var self = this; + var _this = this; var Promise = PromiseProvider.get(); return new Promise.ES6(function (resolve, reject) { if (!Model.mapReduce.schema) { @@ -2031,12 +2032,12 @@ Model.mapReduce = function mapReduce(o, callback) { if (o.query) { var q = new Query(o.query); - q.cast(self); + q.cast(_this); o.query = q._conditions; q = undefined; } - self.collection.mapReduce(null, null, o, function (err, ret, stats) { + _this.collection.mapReduce(null, null, o, function (err, ret, stats) { if (err) { callback && callback(err); reject(err); @@ -2049,8 +2050,8 @@ Model.mapReduce = function mapReduce(o, callback) { '_mapreduce_' + ret.collectionName , Model.mapReduce.schema , ret.collectionName - , self.db - , self.base); + , _this.db + , _this.base); model._mapreduce = true; @@ -2094,12 +2095,12 @@ Model.mapReduce = function mapReduce(o, callback) { */ Model.geoNear = function (near, options, callback) { - if ('function' == typeof options) { + if (typeof options === 'function') { callback = options; options = {}; } - var self = this; + var _this = this; var Promise = PromiseProvider.get(); if (!near) { return new Promise.ES6(function (resolve, reject) { @@ -2110,7 +2111,6 @@ Model.geoNear = function (near, options, callback) { } var x, y; - var _this = this; return new Promise.ES6(function (resolve, reject) { var handler = function (err, res) { @@ -2127,7 +2127,7 @@ Model.geoNear = function (near, options, callback) { var count = res.results.length; // if there are no results, fulfill the promise now - if (count == 0) { + if (count === 0) { resolve(res.results, res.stats); callback && callback(null, res.results, res.stats); return; @@ -2136,7 +2136,7 @@ Model.geoNear = function (near, options, callback) { var errSeen = false; for (var i = 0; i < res.results.length; i++) { var temp = res.results[i].obj; - res.results[i].obj = new self(); + res.results[i].obj = new _this(); res.results[i].obj.init(temp, function (err) { if (err && !errSeen) { errSeen = true; @@ -2164,7 +2164,7 @@ Model.geoNear = function (near, options, callback) { y = near[1]; _this.collection.geoNear(x, y, options, handler); } else { - if (near.type != 'Point' || !Array.isArray(near.coordinates)) { + if (near.type !== 'Point' || !Array.isArray(near.coordinates)) { error = new Error('Must pass either a legacy coordinate array or ' + 'GeoJSON Point to geoNear'); reject(error); @@ -2221,7 +2221,7 @@ Model.aggregate = function aggregate() { aggregate, callback; - if ('function' === typeof args[args.length - 1]) { + if (typeof args[args.length - 1] === 'function') { callback = args.pop(); } @@ -2233,7 +2233,7 @@ Model.aggregate = function aggregate() { aggregate.model(this); - if ('undefined' === typeof callback) { + if (typeof callback === 'undefined') { return aggregate; } @@ -2266,16 +2266,16 @@ Model.aggregate = function aggregate() { */ Model.geoSearch = function (conditions, options, callback) { - if ('function' == typeof options) { + if (typeof options === 'function') { callback = options; options = {}; } - var self = this; + var _this = this; var Promise = PromiseProvider.get(); return new Promise.ES6(function (resolve, reject) { var error; - if (conditions == undefined || !utils.isObject(conditions)) { + if (conditions === undefined || !utils.isObject(conditions)) { error = new Error('Must pass conditions to geoSearch'); } else if (!options.near) { error = new Error('Must specify the near option in geoSearch'); @@ -2292,7 +2292,7 @@ Model.geoSearch = function (conditions, options, callback) { // send the conditions in the options object options.search = conditions; - self.collection.geoHaystackSearch(options.near[0], options.near[1], options, function (err, res) { + _this.collection.geoHaystackSearch(options.near[0], options.near[1], options, function (err, res) { // have to deal with driver problem. Should be fixed in a soon-ish release // (7/8/2013) if (err) { @@ -2311,7 +2311,7 @@ Model.geoSearch = function (conditions, options, callback) { var errSeen = false; for (var i = 0; i < res.results.length; i++) { var temp = res.results[i]; - res.results[i] = new self(); + res.results[i] = new _this(); res.results[i].init(temp, {}, function (err) { if (err && !errSeen) { callback && callback(err); @@ -2439,7 +2439,7 @@ function _populate(model, docs, paths, cb) { var path; while (i--) { path = paths[i]; - if ('function' === typeof path.model) { + if (typeof path.model === 'function') { model = path.model; } populate(model, docs, path, subPopulate.call(model, docs, path, next)); @@ -2466,7 +2466,7 @@ function _populate(model, docs, paths, cb) { * @api private */ function subPopulate(docs, options, cb) { - var model = this; + var _this = this; var prefix = options.path + '.'; var pop = options.populate; @@ -2497,18 +2497,18 @@ function subPopulate(docs, options, cb) { subOptions.path = prefix + subOptions.path; } - var schema = model.schema._getSchema(prefix); + var schema = _this.schema._getSchema(prefix); if (typeof subOptions.model === 'string') { - subOptions.model = model.model(subOptions.model); + subOptions.model = _this.model(subOptions.model); } else if (schema && schema.caster && schema.caster.options && schema.caster.options.ref) { - var subSchema = model.model(schema.caster.options.ref).schema. + var subSchema = _this.model(schema.caster.options.ref).schema. _getSchema(subOptions._originalPath); if (subSchema && subSchema.options && subSchema.options.ref) { - subOptions.model = model.model(subSchema.options.ref); + subOptions.model = _this.model(subSchema.options.ref); } } - Model.populate.call(subOptions.model || model, docs, subOptions, next); + Model.populate.call(subOptions.model || _this, docs, subOptions, next); }); }; } @@ -2602,7 +2602,7 @@ function populate(model, docs, options, cb) { // override the exclusion from the query so we can use the _id // for document matching during assignment. we'll delete the // _id back off before returning the result. - if ('string' == typeof select) { + if (typeof select === 'string') { select = select.replace(excludeIdRegGlobal, ' '); } else { // preserve original select conditions by copying @@ -2869,7 +2869,7 @@ function valueFilter(val, assignmentOpts) { function maybeRemoveId(subdoc, assignmentOpts) { if (assignmentOpts.excludeId) { - if ('function' == typeof subdoc.setValue) { + if ('function' === typeof subdoc.setValue) { delete subdoc._doc._id; } else { delete subdoc._id; @@ -2888,11 +2888,11 @@ function isDoc(doc) { } var type = typeof doc; - if ('string' == type) { + if (type === 'string') { return false; } - if ('number' == type) { + if (type === 'number') { return false; } @@ -2900,7 +2900,7 @@ function isDoc(doc) { return false; } - if ('ObjectID' == doc.constructor.name) { + if (doc.constructor.name === 'ObjectID') { return false; } @@ -3110,28 +3110,28 @@ var applyStatics = function (model, schema) { Model.__subclass = function subclass(conn, schema, collection) { // subclass model using this connection and collection name - var model = this; + var _this = this; var Model = function Model(doc, fields, skipId) { if (!(this instanceof Model)) { return new Model(doc, fields, skipId); } - model.call(this, doc, fields, skipId); + _this.call(this, doc, fields, skipId); }; - Model.__proto__ = model; - Model.prototype.__proto__ = model.prototype; + Model.__proto__ = _this; + Model.prototype.__proto__ = _this.prototype; Model.db = Model.prototype.db = conn; - var s = schema && 'string' != typeof schema + var s = schema && typeof schema !== 'string' ? schema - : model.prototype.schema; + : _this.prototype.schema; var options = s.options || {}; if (!collection) { - collection = model.prototype.schema.get('collection') - || utils.toCollectionName(model.modelName, options); + collection = _this.prototype.schema.get('collection') + || utils.toCollectionName(_this.modelName, options); } var collectionOptions = { diff --git a/lib/query.js b/lib/query.js index b171e45dc30..ac601b74adb 100644 --- a/lib/query.js +++ b/lib/query.js @@ -877,7 +877,7 @@ Query.prototype.setOptions = function (options, overwrite) { return this; } - if (!(options && 'Object' == options.constructor.name)) { + if (!(options && options.constructor.name === 'Object')) { return this; } @@ -1027,7 +1027,7 @@ Query.prototype._find = function (callback) { var fields = this._fieldsForExec(); var options = this._mongooseOptions; - var self = this; + var _this = this; var cb = function (err, docs) { if (err) { @@ -1041,16 +1041,16 @@ Query.prototype._find = function (callback) { if (!options.populate) { return true === options.lean ? callback(null, docs) - : completeMany(self.model, docs, fields, self, null, callback); + : completeMany(_this.model, docs, fields, _this, null, callback); } - var pop = helpers.preparePopulationOptionsMQ(self, options); + var pop = helpers.preparePopulationOptionsMQ(_this, options); pop.__noPromise = true; - self.model.populate(docs, pop, function (err, docs) { + _this.model.populate(docs, pop, function (err, docs) { if (err) return callback(err); return true === options.lean ? callback(null, docs) - : completeMany(self.model, docs, fields, self, pop, callback); + : completeMany(_this.model, docs, fields, _this, pop, callback); }); }; @@ -1073,7 +1073,7 @@ Query.prototype._find = function (callback) { */ Query.prototype.find = function (conditions, callback) { - if ('function' == typeof conditions) { + if (typeof conditions === 'function') { callback = conditions; conditions = {}; } @@ -1148,10 +1148,10 @@ Query.prototype._findOne = function (callback) { var options = this._mongooseOptions; var projection = this._fieldsForExec(); - var self = this; + var _this = this; // don't pass in the conditions because we already merged them in - Query.base.findOne.call(self, {}, function (err, doc) { + Query.base.findOne.call(_this, {}, function (err, doc) { if (err) { return callback(err); } @@ -1162,19 +1162,19 @@ Query.prototype._findOne = function (callback) { if (!options.populate) { return true === options.lean ? callback(null, doc) - : completeOne(self.model, doc, null, projection, self, null, callback); + : completeOne(_this.model, doc, null, projection, _this, null, callback); } - var pop = helpers.preparePopulationOptionsMQ(self, options); + var pop = helpers.preparePopulationOptionsMQ(_this, options); pop.__noPromise = true; - self.model.populate(doc, pop, function (err, doc) { + _this.model.populate(doc, pop, function (err, doc) { if (err) { return callback(err); } return true === options.lean ? callback(null, doc) - : completeOne(self.model, doc, null, projection, self, pop, callback); + : completeOne(_this.model, doc, null, projection, _this, pop, callback); }); }); }; @@ -1204,16 +1204,16 @@ Query.prototype._findOne = function (callback) { */ Query.prototype.findOne = function (conditions, projection, options, callback) { - if ('function' == typeof conditions) { + if (typeof conditions === 'function') { callback = conditions; conditions = null; projection = null; options = null; - } else if ('function' == typeof projection) { + } else if (typeof projection === 'function') { callback = projection; options = null; projection = null; - } else if ('function' == typeof options) { + } else if (typeof options === 'function') { callback = options; options = null; } @@ -1304,7 +1304,7 @@ Query.prototype._count = function (callback) { */ Query.prototype.count = function (conditions, callback) { - if ('function' == typeof conditions) { + if (typeof conditions === 'function') { callback = conditions; conditions = undefined; } @@ -1347,10 +1347,10 @@ Query.prototype.count = function (conditions, callback) { Query.prototype.distinct = function (field, conditions, callback) { if (!callback) { - if ('function' === typeof conditions) { + if (typeof conditions === 'function') { callback = conditions; conditions = undefined; - } else if ('function' === typeof field) { + } else if (typeof field === 'function') { callback = field; field = undefined; conditions = undefined; @@ -1422,7 +1422,7 @@ Query.prototype.sort = function (arg) { // workaround for gh-2374 when sort is called after count // if previous operation is count, we ignore - if (this.op == 'count') { + if (this.op === 'count') { delete this.op; } return Query.base.sort.call(this, nArg); @@ -1463,12 +1463,12 @@ Query.prototype.sort = function (arg) { */ Query.prototype.remove = function (cond, callback) { - if ('function' == typeof cond) { + if (typeof cond === 'function') { callback = cond; cond = null; } - var cb = 'function' == typeof callback; + var cb = typeof callback === 'function'; try { this.cast(this.model); @@ -1571,13 +1571,13 @@ Query.prototype.findOneAndUpdate = function (criteria, doc, options, callback) { switch (arguments.length) { case 3: - if ('function' == typeof options) { + if (typeof options === 'function') { callback = options; options = {}; } break; case 2: - if ('function' == typeof doc) { + if (typeof doc === 'function') { callback = doc; doc = criteria; criteria = undefined; @@ -1585,7 +1585,7 @@ Query.prototype.findOneAndUpdate = function (criteria, doc, options, callback) { options = undefined; break; case 1: - if ('function' == typeof criteria) { + if (typeof criteria === 'function') { callback = criteria; criteria = options = doc = undefined; } else { @@ -1666,13 +1666,13 @@ Query.prototype.findOneAndRemove = function (conditions, options, callback) { switch (arguments.length) { case 2: - if ('function' == typeof options) { + if (typeof options === 'function') { callback = options; options = {}; } break; case 1: - if ('function' == typeof conditions) { + if (typeof conditions === 'function') { callback = conditions; conditions = undefined; options = undefined; @@ -1715,13 +1715,13 @@ Query.prototype._findOneAndRemove = function (callback) { */ Query.prototype._findAndModify = function (type, callback) { - if ('function' != typeof callback) { + if (typeof callback !== 'function') { throw new Error('Expected callback in _findAndModify'); } var model = this.model; var schema = model.schema; - var self = this; + var _this = this; var castedQuery; var castedDoc; var fields; @@ -1739,7 +1739,7 @@ Query.prototype._findAndModify = function (type, callback) { this._mongooseOptions.strict = opts.strict; } - if ('remove' == type) { + if (type === 'remove') { opts.remove = true; } else { if (!('new' in opts)) { @@ -1778,7 +1778,6 @@ Query.prototype._findAndModify = function (type, callback) { this._applyPaths(); - self = this; var options = this._mongooseOptions; if (this._fields) { @@ -1807,19 +1806,19 @@ Query.prototype._findAndModify = function (type, callback) { if (!options.populate) { return true === options.lean ? callback(null, doc) - : completeOne(self.model, doc, res, fields, self, null, callback); + : completeOne(_this.model, doc, res, fields, _this, null, callback); } - var pop = helpers.preparePopulationOptionsMQ(self, options); + var pop = helpers.preparePopulationOptionsMQ(_this, options); pop.__noPromise = true; - self.model.populate(doc, pop, function (err, doc) { + _this.model.populate(doc, pop, function (err, doc) { if (err) { return callback(err); } return true === options.lean ? callback(null, doc) - : completeOne(self.model, doc, res, fields, self, pop, callback); + : completeOne(_this.model, doc, res, fields, _this, pop, callback); }); }; @@ -1828,7 +1827,7 @@ Query.prototype._findAndModify = function (type, callback) { if (error) { return callback(error); } - self._collection.findAndModify(castedQuery, castedDoc, opts, utils.tick(function (error, res) { + _this._collection.findAndModify(castedQuery, castedDoc, opts, utils.tick(function (error, res) { return cb(error, res ? res.value : res, res); })); }); @@ -1998,17 +1997,17 @@ Query.prototype._execUpdate = function (callback) { */ Query.prototype.update = function (conditions, doc, options, callback) { - if ('function' === typeof options) { + if (typeof options === 'function') { // .update(conditions, doc, callback) callback = options; options = null; - } else if ('function' === typeof doc) { + } else if (typeof doc === 'function') { // .update(doc, callback); callback = doc; doc = conditions; conditions = {}; options = null; - } else if ('function' === typeof conditions) { + } else if (typeof conditions === 'function') { // .update(callback) callback = conditions; conditions = undefined; @@ -2129,10 +2128,10 @@ Query.prototype.exec = function exec(op, callback) { var Promise = PromiseProvider.get(); var _this = this; - if ('function' == typeof op) { + if (typeof op === 'function') { callback = op; op = null; - } else if ('string' == typeof op) { + } else if (typeof op === 'string') { this.op = op; } @@ -2266,7 +2265,7 @@ Query.prototype._castUpdate = function _castUpdate(obj, overwrite) { val.constructor.name === 'Object' && (!overwrite || hasDollarKey)) { hasKeys |= this._walkUpdatePath(val, op); - } else if (overwrite && 'Object' === ret.constructor.name) { + } else if (overwrite && ret.constructor.name === 'Object') { // if we are just using overwrite, cast the query and then we will // *always* return the value, even if it is an empty object. We need to // set hasKeys above because we need to account for the case where the @@ -2312,7 +2311,7 @@ Query.prototype._walkUpdatePath = function _walkUpdatePath(obj, op, pref) { key = keys[i]; val = obj[key]; - if (val && 'Object' === val.constructor.name) { + if (val && val.constructor.name === 'Object') { // watch for embedded doc schemas schema = this._getSchema(prefix + key); if (schema && schema.caster && op in castOps) { @@ -2617,7 +2616,7 @@ Query.prototype._applyPaths = function applyPaths() { ki = keys.length; while (ki--) { - if ('+' == keys[ki][0]) continue; + if ('+' === keys[ki][0]) continue; exclude = 0 === fields[keys[ki]]; break; } @@ -2631,7 +2630,7 @@ Query.prototype._applyPaths = function applyPaths() { seen = []; var analyzePath = function (path, type) { - if ('boolean' != typeof type.selected) return; + if (typeof type.selected !== 'boolean') return; var plusPath = '+' + path; if (fields && plusPath in fields) { @@ -2770,7 +2769,7 @@ Query.prototype.maxscan = Query.base.maxScan; Query.prototype.tailable = function (val, opts) { // we need to support the tailable({ awaitdata : true }) as well as the // tailable(true, {awaitdata :true}) syntax that mquery does not support - if (val && val.constructor.name == 'Object') { + if (val && val.constructor.name === 'Object') { opts = val; val = true; } @@ -2907,11 +2906,11 @@ Query.prototype.near = function () { if (arguments.length === 1) { if (Array.isArray(arguments[0])) { params.push({center: arguments[0], spherical: sphere}); - } else if ('string' == typeof arguments[0]) { + } else if (typeof arguments[0] === 'string') { // just passing a path params.push(arguments[0]); } else if (utils.isObject(arguments[0])) { - if ('boolean' != typeof arguments[0].spherical) { + if (typeof arguments[0].spherical !== 'boolean') { arguments[0].spherical = sphere; } params.push(arguments[0]); @@ -2919,14 +2918,14 @@ Query.prototype.near = function () { throw new TypeError('invalid argument'); } } else if (arguments.length === 2) { - if ('number' == typeof arguments[0] && 'number' == typeof arguments[1]) { + if (typeof arguments[0] === 'number' && typeof arguments[1] === 'number') { params.push({center: [arguments[0], arguments[1]], spherical: sphere}); - } else if ('string' == typeof arguments[0] && Array.isArray(arguments[1])) { + } else if (typeof arguments[0] === 'string' && Array.isArray(arguments[1])) { params.push(arguments[0]); params.push({center: arguments[1], spherical: sphere}); - } else if ('string' == typeof arguments[0] && utils.isObject(arguments[1])) { + } else if (typeof arguments[0] === 'string' && utils.isObject(arguments[1])) { params.push(arguments[0]); - if ('boolean' != typeof arguments[1].spherical) { + if (typeof arguments[1].spherical !== 'boolean') { arguments[1].spherical = sphere; } params.push(arguments[1]); @@ -2934,8 +2933,8 @@ Query.prototype.near = function () { throw new TypeError('invalid argument'); } } else if (arguments.length === 3) { - if ('string' == typeof arguments[0] && 'number' == typeof arguments[1] - && 'number' == typeof arguments[2]) { + if (typeof arguments[0] === 'string' && typeof arguments[1] === 'number' + && typeof arguments[2] === 'number') { params.push(arguments[0]); params.push({center: [arguments[1], arguments[2]], spherical: sphere}); } else { @@ -3091,11 +3090,11 @@ Query.prototype.center = Query.base.circle; */ Query.prototype.centerSphere = function () { - if (arguments[0] && arguments[0].constructor.name == 'Object') { + if (arguments[0] && arguments[0].constructor.name === 'Object') { arguments[0].spherical = true; } - if (arguments[1] && arguments[1].constructor.name == 'Object') { + if (arguments[1] && arguments[1].constructor.name === 'Object') { arguments[1].spherical = true; } diff --git a/lib/querystream.js b/lib/querystream.js index 4355ee9fea8..ca62194e4a9 100644 --- a/lib/querystream.js +++ b/lib/querystream.js @@ -64,14 +64,14 @@ function QueryStream(query, options) { this._buffer = null; this._inline = T_INIT; this._running = false; - this._transform = options && 'function' == typeof options.transform + this._transform = options && typeof options.transform === 'function' ? options.transform : K; // give time to hook up events - var self = this; + var _this = this; process.nextTick(function () { - self._init(); + _this._init(); }); } @@ -118,23 +118,23 @@ QueryStream.prototype._init = function () { var query = this.query, model = query.model, options = query._optionsForExec(model), - self = this; + _this = this; try { query.cast(model); } catch (err) { - return self.destroy(err); + return _this.destroy(err); } - self._fields = utils.clone(query._fields); - options.fields = query._castFields(self._fields); + _this._fields = utils.clone(query._fields); + options.fields = query._castFields(_this._fields); model.collection.find(query._conditions, options, function (err, cursor) { if (err) { - return self.destroy(err); + return _this.destroy(err); } - self._cursor = cursor; - self._next(); + _this._cursor = cursor; + _this._next(); }); }; @@ -235,8 +235,8 @@ QueryStream.prototype._onNextObject = function _onNextObject(err, doc) { createAndEmit(this, null, doc); } - var self = this; - var pop = helpers.preparePopulationOptionsMQ(self.query, self.query._mongooseOptions); + var _this = this; + var pop = helpers.preparePopulationOptionsMQ(_this.query, _this.query._mongooseOptions); // Hack to work around gh-3108 pop.forEach(function (option) { @@ -244,13 +244,13 @@ QueryStream.prototype._onNextObject = function _onNextObject(err, doc) { }); pop.__noPromise = true; - self.query.model.populate(doc, pop, function (err, doc) { + _this.query.model.populate(doc, pop, function (err, doc) { if (err) { - return self.destroy(err); + return _this.destroy(err); } return true === opts.lean ? - emit(self, doc) : - createAndEmit(self, pop, doc); + emit(_this, doc) : + createAndEmit(_this, pop, doc); }); }; diff --git a/lib/schema.js b/lib/schema.js index 3bdea04983a..9c88b7f49ce 100644 --- a/lib/schema.js +++ b/lib/schema.js @@ -377,7 +377,7 @@ Schema.prototype.add = function add(obj, prefix) { } if (utils.isObject(obj[key]) && - (!obj[key].constructor || 'Object' == utils.getFunctionName(obj[key].constructor)) && + (!obj[key].constructor || 'Object' === utils.getFunctionName(obj[key].constructor)) && (!obj[key][this.options.typeKey] || (this.options.typeKey === 'type' && obj[key].type.type))) { if (Object.keys(obj[key]).length) { // nested object { last: { name: String }} @@ -455,7 +455,7 @@ warnings.increment = '`increment` should not be used as a schema path name ' + */ Schema.prototype.path = function (path, obj) { - if (obj == undefined) { + if (obj === undefined) { if (this.paths[path]) { return this.paths[path]; } @@ -490,7 +490,7 @@ Schema.prototype.path = function (path, obj) { if (!branch[sub]) { branch[sub] = {}; } - if ('object' != typeof branch[sub]) { + if (typeof branch[sub] !== 'object') { var msg = 'Cannot set nested path `' + path + '`. ' + 'Parent path `' + subpaths.slice(0, i).concat([sub]).join('.') @@ -528,7 +528,7 @@ Schema.prototype.path = function (path, obj) { Schema.interpretAsType = function (path, obj, options) { if (obj.constructor) { var constructorName = utils.getFunctionName(obj.constructor); - if (constructorName != 'Object') { + if (constructorName !== 'Object') { var oldObj = obj; obj = {}; obj[options.typeKey] = oldObj; @@ -542,13 +542,13 @@ Schema.interpretAsType = function (path, obj, options) { ? obj[options.typeKey] : {}; - if ('Object' == utils.getFunctionName(type.constructor) || 'mixed' == type) { + if ('Object' === utils.getFunctionName(type.constructor) || type === 'mixed') { return new MongooseTypes.Mixed(path, obj); } - if (Array.isArray(type) || Array == type || 'array' == type) { + if (Array.isArray(type) || Array === type || type === 'array') { // if it was specified through { type } look for `cast` - var cast = (Array == type || 'array' == type) + var cast = (Array === type || type === 'array') ? obj.cast : type[0]; @@ -556,10 +556,10 @@ Schema.interpretAsType = function (path, obj, options) { return new MongooseTypes.DocumentArray(path, cast, obj); } - if ('string' == typeof cast) { + if (typeof cast === 'string') { cast = MongooseTypes[cast.charAt(0).toUpperCase() + cast.substring(1)]; } else if (cast && (!cast[options.typeKey] || (options.typeKey === 'type' && cast.type.type)) - && 'Object' == utils.getFunctionName(cast.constructor) + && 'Object' === utils.getFunctionName(cast.constructor) && Object.keys(cast).length) { // The `minimize` and `typeKey` options propagate to child schemas // declared inline, like `{ arr: [{ val: { $type: String } }] }`. @@ -583,7 +583,7 @@ Schema.interpretAsType = function (path, obj, options) { if (Buffer.isBuffer(type)) { name = 'Buffer'; } else { - name = 'string' == typeof type + name = typeof type === 'string' ? type // If not string, `type` is a function. Outside of IE, function.name // gives you the function name. In IE, you need to compute it @@ -816,7 +816,7 @@ Schema.prototype.queue = function (name, args) { * }) * * toySchema.pre('validate', function (next) { - * if (this.name != 'Woody') this.name = 'Woody'; + * if (this.name !== 'Woody') this.name = 'Woody'; * next(); * }) * @@ -873,10 +873,10 @@ Schema.prototype.post = function (method, fn) { return this.queue('post', [arguments[0], function (next) { // wrap original function so that the callback goes last, // for compatibility with old code that is using synchronous post hooks - var self = this; + var _this = this; var args = Array.prototype.slice.call(arguments, 1); fn.call(this, this, function (err) { - return next.apply(self, [err].concat(args)); + return next.apply(_this, [err].concat(args)); }); }]); }; @@ -928,7 +928,7 @@ Schema.prototype.plugin = function (fn, opts) { */ Schema.prototype.method = function (name, fn) { - if ('string' != typeof name) { + if (typeof name !== 'string') { for (var i in name) { this.methods[i] = name[i]; } @@ -961,7 +961,7 @@ Schema.prototype.method = function (name, fn) { */ Schema.prototype.static = function (name, fn) { - if ('string' != typeof name) { + if (typeof name !== 'string') { for (var i in name) { this.statics[i] = name[i]; } @@ -1092,11 +1092,11 @@ Schema.prototype.indexes = function () { } else { index = path._index; - if (false !== index && null != index) { + if (false !== index && null !== index) { field = {}; isObject = utils.isObject(index); options = isObject ? index : {}; - type = 'string' == typeof index ? index : + type = typeof index === 'string' ? index : isObject ? index.type : false; @@ -1222,8 +1222,8 @@ Schema.prototype.remove = function (path) { */ Schema.prototype._getSchema = function (path) { - var schema = this; - var pathschema = schema.path(path); + var _this = this; + var pathschema = _this.path(path); if (pathschema) { return pathschema; @@ -1263,7 +1263,7 @@ Schema.prototype._getSchema = function (path) { return foundschema; } } - })(path.split('.'), schema); + })(path.split('.'), _this); }; /*! diff --git a/lib/schema/array.js b/lib/schema/array.js index 3bdefa7528b..b33bea42416 100644 --- a/lib/schema/array.js +++ b/lib/schema/array.js @@ -45,7 +45,7 @@ function SchemaArray(key, cast, options) { } // support { type: 'String' } - var name = 'string' == typeof cast + var name = typeof cast === 'string' ? cast : utils.getFunctionName(cast); @@ -62,18 +62,18 @@ function SchemaArray(key, cast, options) { SchemaType.call(this, key, options, 'Array'); - var self = this, + var _this = this, defaultArr, fn; if (this.defaultValue) { defaultArr = this.defaultValue; - fn = 'function' == typeof defaultArr; + fn = typeof defaultArr === 'function'; } this.default(function () { var arr = fn ? defaultArr() : defaultArr || []; - return new MongooseArray(arr, self.path, this); + return new MongooseArray(arr, _this.path, this); }); } @@ -135,7 +135,7 @@ SchemaArray.prototype.cast = function (value, doc, init) { for (var i = 0, l = indexes.length; i < l; ++i) { var pathIndex = indexes[i][0][this.path]; - if ('2dsphere' === pathIndex || '2d' === pathIndex) { + if ('2dsphere' === pathIndex || pathIndex === '2d') { return; } } @@ -225,8 +225,6 @@ function castToNumber(val) { } function castArraysOfNumbers(arr, self) { - self || (self = this); - arr.forEach(function (v, i) { if (Array.isArray(v)) { castArraysOfNumbers(v, self); @@ -269,10 +267,10 @@ function cast$geometry(val, self) { } function cast$within(val) { - var self = this; + var _this = this; if (val.$maxDistance) { - val.$maxDistance = castToNumber.call(self, val.$maxDistance); + val.$maxDistance = castToNumber.call(_this, val.$maxDistance); } if (val.$box || val.$polygon) { diff --git a/lib/schema/boolean.js b/lib/schema/boolean.js index 6692facfde6..30d83a2ddb5 100644 --- a/lib/schema/boolean.js +++ b/lib/schema/boolean.js @@ -54,13 +54,13 @@ SchemaBoolean.prototype.cast = function (value) { if (null === value) { return value; } - if ('0' === value) { + if (value === '0') { return false; } - if ('true' === value) { + if (value === 'true') { return true; } - if ('false' === value) { + if (value === 'false') { return false; } return !!value; diff --git a/lib/schema/buffer.js b/lib/schema/buffer.js index c7b46ea9fd9..ce83728b485 100644 --- a/lib/schema/buffer.js +++ b/lib/schema/buffer.js @@ -47,7 +47,7 @@ SchemaBuffer.prototype.constructor = SchemaBuffer; SchemaBuffer.prototype.checkRequired = function (value, doc) { if (SchemaType._isRef(this, value, doc, true)) { - return null != value; + return !!value; } return !!(value && value.length); }; @@ -66,7 +66,7 @@ SchemaBuffer.prototype.cast = function (value, doc, init) { if (SchemaType._isRef(this, value, doc, init)) { // wait! we may need to cast this to a document - if (null == value) { + if (value === null || value === void 0) { return value; } @@ -125,7 +125,7 @@ SchemaBuffer.prototype.cast = function (value, doc, init) { } var type = typeof value; - if ('string' == type || 'number' == type || Array.isArray(value)) { + if ('string' === type || 'number' === type || Array.isArray(value)) { if (type === 'number') { value = [value]; } diff --git a/lib/schema/date.js b/lib/schema/date.js index 48ebe51993c..158afbd8383 100644 --- a/lib/schema/date.js +++ b/lib/schema/date.js @@ -121,17 +121,17 @@ SchemaDate.prototype.checkRequired = function (value) { SchemaDate.prototype.min = function (value, message) { if (this.minValidator) { this.validators = this.validators.filter(function (v) { - return v.validator != this.minValidator; + return v.validator !== this.minValidator; }, this); } if (value) { var msg = message || errorMessages.Date.min; msg = msg.replace(/{MIN}/, (value === Date.now ? 'Date.now()' : this.cast(value).toString())); - var self = this; + var _this = this; this.validators.push({ validator: this.minValidator = function (val) { - var min = (value === Date.now ? value() : self.cast(value)); + var min = (value === Date.now ? value() : _this.cast(value)); return val === null || val.valueOf() >= min.valueOf(); }, message: msg, @@ -177,17 +177,17 @@ SchemaDate.prototype.min = function (value, message) { SchemaDate.prototype.max = function (value, message) { if (this.maxValidator) { this.validators = this.validators.filter(function (v) { - return v.validator != this.maxValidator; + return v.validator !== this.maxValidator; }, this); } if (value) { var msg = message || errorMessages.Date.max; msg = msg.replace(/{MAX}/, (value === Date.now ? 'Date.now()' : this.cast(value).toString())); - var self = this; + var _this = this; this.validators.push({ validator: this.maxValidator = function (val) { - var max = (value === Date.now ? value() : self.cast(value)); + var max = (value === Date.now ? value() : _this.cast(value)); return val === null || val.valueOf() <= max.valueOf(); }, message: msg, @@ -208,7 +208,7 @@ SchemaDate.prototype.max = function (value, message) { SchemaDate.prototype.cast = function (value) { // If null or undefined - if (value == null || value === '') { + if (value === null || value === void 0 || value === '') { return null; } @@ -218,7 +218,7 @@ SchemaDate.prototype.cast = function (value) { var date; - if (value instanceof Number || 'number' == typeof value + if (value instanceof Number || typeof value === 'number' || String(value) == Number(value)) { // support for timestamps date = new Date(Number(value)); diff --git a/lib/schema/number.js b/lib/schema/number.js index e7daeee85de..d4f6276a8e4 100644 --- a/lib/schema/number.js +++ b/lib/schema/number.js @@ -44,9 +44,9 @@ SchemaNumber.prototype.constructor = SchemaNumber; SchemaNumber.prototype.checkRequired = function checkRequired(value, doc) { if (SchemaType._isRef(this, value, doc, true)) { - return null != value; + return !!value; } - return typeof value == 'number' || value instanceof Number; + return typeof value === 'number' || value instanceof Number; }; /** @@ -83,7 +83,7 @@ SchemaNumber.prototype.checkRequired = function checkRequired(value, doc) { SchemaNumber.prototype.min = function (value, message) { if (this.minValidator) { this.validators = this.validators.filter(function (v) { - return v.validator != this.minValidator; + return v.validator !== this.minValidator; }, this); } @@ -137,11 +137,11 @@ SchemaNumber.prototype.min = function (value, message) { SchemaNumber.prototype.max = function (value, message) { if (this.maxValidator) { this.validators = this.validators.filter(function (v) { - return v.validator != this.maxValidator; + return v.validator !== this.maxValidator; }, this); } - if (null != value) { + if (value != null) { var msg = message || errorMessages.Number.max; msg = msg.replace(/{MAX}/, value); this.validators.push({ @@ -170,7 +170,7 @@ SchemaNumber.prototype.cast = function (value, doc, init) { if (SchemaType._isRef(this, value, doc, init)) { // wait! we may need to cast this to a document - if (null == value) { + if (value === null || value === void 0) { return value; } @@ -183,7 +183,7 @@ SchemaNumber.prototype.cast = function (value, doc, init) { } // setting a populated path - if ('number' == typeof value) { + if (typeof value === 'number') { return value; } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { throw new CastError('number', value, this.path); @@ -217,7 +217,7 @@ SchemaNumber.prototype.cast = function (value, doc, init) { if (val instanceof Number) { return val; } - if ('number' == typeof val) { + if (typeof val === 'number') { return val; } if (val.toString && !Array.isArray(val) && @@ -238,12 +238,12 @@ function handleSingle(val) { } function handleArray(val) { - var self = this; + var _this = this; if (!Array.isArray(val)) { return [this.cast(val)]; } return val.map(function (m) { - return self.cast(m); + return _this.cast(m); }); } @@ -278,7 +278,7 @@ SchemaNumber.prototype.castForQuery = function ($conditional, val) { return handler.call(this, val); } val = this.cast($conditional); - return val == null ? val : val; + return val; }; /*! diff --git a/lib/schema/objectid.js b/lib/schema/objectid.js index 22c5fbda7f7..e5b14f0b7e0 100644 --- a/lib/schema/objectid.js +++ b/lib/schema/objectid.js @@ -61,7 +61,7 @@ ObjectId.prototype.auto = function (turnOn) { ObjectId.prototype.checkRequired = function checkRequired(value, doc) { if (SchemaType._isRef(this, value, doc, true)) { - return null != value; + return !!value; } return value instanceof oid; }; @@ -79,7 +79,7 @@ ObjectId.prototype.cast = function (value, doc, init) { if (SchemaType._isRef(this, value, doc, init)) { // wait! we may need to cast this to a document - if (null == value) { + if (value === null || value === void 0) { return value; } @@ -110,7 +110,7 @@ ObjectId.prototype.cast = function (value, doc, init) { } // If null or undefined - if (value == null) { + if (value === null || value === void 0) { return value; } diff --git a/lib/schema/operators/bitwise.js b/lib/schema/operators/bitwise.js index 0818f84d196..e0f535ae641 100644 --- a/lib/schema/operators/bitwise.js +++ b/lib/schema/operators/bitwise.js @@ -12,23 +12,23 @@ function handleBitwiseOperator(val) { var _this = this; if (Array.isArray(val)) { return val.map(function (v) { - return _castNumber(_this, v); + return _castNumber(_this.path, v); }); } else if (Buffer.isBuffer(val)) { return val; } // Assume trying to cast to number - return _castNumber(_this, val); + return _castNumber(_this.path, val); } /*! * ignore */ -function _castNumber(_this, num) { +function _castNumber(path, num) { var v = Number(num); if (isNaN(v)) { - throw new CastError('number', num, _this.path); + throw new CastError('number', num, path); } return v; } diff --git a/lib/schema/string.js b/lib/schema/string.js index 6abbd9e6813..696885ff67c 100644 --- a/lib/schema/string.js +++ b/lib/schema/string.js @@ -75,7 +75,7 @@ SchemaString.prototype.constructor = SchemaString; SchemaString.prototype.enum = function () { if (this.enumValidator) { this.validators = this.validators.filter(function (v) { - return v.validator != this.enumValidator; + return v.validator !== this.enumValidator; }, this); this.enumValidator = false; } @@ -131,7 +131,7 @@ SchemaString.prototype.enum = function () { SchemaString.prototype.lowercase = function () { return this.set(function (v, self) { - if ('string' != typeof v) { + if (typeof v !== 'string') { v = self.cast(v); } if (v) { @@ -157,7 +157,7 @@ SchemaString.prototype.lowercase = function () { SchemaString.prototype.uppercase = function () { return this.set(function (v, self) { - if ('string' != typeof v) { + if (typeof v !== 'string') { v = self.cast(v); } if (v) { @@ -187,7 +187,7 @@ SchemaString.prototype.uppercase = function () { SchemaString.prototype.trim = function () { return this.set(function (v, self) { - if ('string' != typeof v) { + if (typeof v !== 'string') { v = self.cast(v); } if (v) { @@ -231,11 +231,11 @@ SchemaString.prototype.trim = function () { SchemaString.prototype.minlength = function (value, message) { if (this.minlengthValidator) { this.validators = this.validators.filter(function (v) { - return v.validator != this.minlengthValidator; + return v.validator !== this.minlengthValidator; }, this); } - if (null != value) { + if (null !== value) { var msg = message || errorMessages.String.minlength; msg = msg.replace(/{MINLENGTH}/, value); this.validators.push({ @@ -285,11 +285,11 @@ SchemaString.prototype.minlength = function (value, message) { SchemaString.prototype.maxlength = function (value, message) { if (this.maxlengthValidator) { this.validators = this.validators.filter(function (v) { - return v.validator != this.maxlengthValidator; + return v.validator !== this.maxlengthValidator; }, this); } - if (null != value) { + if (value != null) { var msg = message || errorMessages.String.maxlength; msg = msg.replace(/{MAXLENGTH}/, value); this.validators.push({ @@ -377,9 +377,9 @@ SchemaString.prototype.match = function match(regExp, message) { SchemaString.prototype.checkRequired = function checkRequired(value, doc) { if (SchemaType._isRef(this, value, doc, true)) { - return null != value; + return !!value; } - return (value instanceof String || typeof value == 'string') && value.length; + return (value instanceof String || typeof value === 'string') && value.length; }; /** @@ -392,7 +392,7 @@ SchemaString.prototype.cast = function (value, doc, init) { if (SchemaType._isRef(this, value, doc, init)) { // wait! we may need to cast this to a document - if (null == value) { + if (value === null) { return value; } @@ -405,7 +405,7 @@ SchemaString.prototype.cast = function (value, doc, init) { } // setting a populated path - if ('string' == typeof value) { + if (typeof value === 'string') { return value; } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { throw new CastError('string', value, this.path); @@ -423,13 +423,13 @@ SchemaString.prototype.cast = function (value, doc, init) { } // If null or undefined - if (value == null) { + if (value === null || value === void 0) { return value; } - if ('undefined' !== typeof value) { + if (typeof value !== 'undefined') { // handle documents being passed - if (value._id && 'string' == typeof value._id) { + if (value._id && typeof value._id === 'string') { return value._id; } @@ -453,12 +453,12 @@ function handleSingle(val) { } function handleArray(val) { - var self = this; + var _this = this; if (!Array.isArray(val)) { return [this.castForQuery(val)]; } return val.map(function (m) { - return self.castForQuery(m); + return _this.castForQuery(m); }); } diff --git a/lib/schematype.js b/lib/schematype.js index 7ed37e2b610..71a32eab11a 100644 --- a/lib/schematype.js +++ b/lib/schematype.js @@ -28,9 +28,9 @@ function SchemaType(path, options, instance) { this.selected; for (var i in options) { - if (this[i] && 'function' == typeof this[i]) { + if (this[i] && typeof this[i] === 'function') { // { unique: true, index: true } - if ('index' == i && this._index) { + if ('index' === i && this._index) { continue; } @@ -145,9 +145,9 @@ SchemaType.prototype.index = function (options) { */ SchemaType.prototype.unique = function (bool) { - if (null == this._index || 'boolean' == typeof this._index) { + if (null === this._index || typeof this._index === 'boolean') { this._index = {}; - } else if ('string' == typeof this._index) { + } else if (typeof this._index === 'string') { this._index = {type: this._index}; } @@ -168,9 +168,9 @@ SchemaType.prototype.unique = function (bool) { */ SchemaType.prototype.text = function (bool) { - if (null == this._index || 'boolean' == typeof this._index) { + if (null === this._index || typeof this._index === 'boolean') { this._index = {}; - } else if ('string' == typeof this._index) { + } else if (typeof this._index === 'string') { this._index = {type: this._index}; } @@ -192,9 +192,9 @@ SchemaType.prototype.text = function (bool) { */ SchemaType.prototype.sparse = function (bool) { - if (null == this._index || 'boolean' == typeof this._index) { + if (null === this._index || typeof this._index === 'boolean') { this._index = {}; - } else if ('string' == typeof this._index) { + } else if (typeof this._index === 'string') { this._index = {type: this._index}; } @@ -208,7 +208,7 @@ SchemaType.prototype.sparse = function (bool) { * ####Example: * * function capitalize (val) { - * if ('string' != typeof val) val = ''; + * if (typeof val !== 'string') val = ''; * return val.charAt(0).toUpperCase() + val.substring(1); * } * @@ -276,7 +276,7 @@ SchemaType.prototype.sparse = function (bool) { */ SchemaType.prototype.set = function (fn) { - if ('function' != typeof fn) { + if (typeof fn !== 'function') { throw new TypeError('A setter must be a function.'); } this.setters.push(fn); @@ -346,7 +346,7 @@ SchemaType.prototype.set = function (fn) { */ SchemaType.prototype.get = function (fn) { - if ('function' != typeof fn) { + if (typeof fn !== 'function') { throw new TypeError('A getter must be a function.'); } this.getters.push(fn); @@ -436,7 +436,7 @@ SchemaType.prototype.get = function (fn) { */ SchemaType.prototype.validate = function (obj, message, type) { - if ('function' == typeof obj || obj && 'RegExp' === utils.getFunctionName(obj.constructor)) { + if (typeof obj === 'function' || obj && 'RegExp' === utils.getFunctionName(obj.constructor)) { var properties; if (message instanceof Object && !type) { properties = utils.clone(message); @@ -508,28 +508,28 @@ SchemaType.prototype.validate = function (obj, message, type) { SchemaType.prototype.required = function (required, message) { if (false === required) { this.validators = this.validators.filter(function (v) { - return v.validator != this.requiredValidator; + return v.validator !== this.requiredValidator; }, this); this.isRequired = false; return this; } - var self = this; + var _this = this; this.isRequired = true; this.requiredValidator = function (v) { // in here, `this` refers to the validating document. // no validation when this path wasn't selected in the query. - if ('isSelected' in this && !this.isSelected(self.path) && !this.isModified(self.path)) { + if ('isSelected' in this && !this.isSelected(_this.path) && !this.isModified(_this.path)) { return true; } - return (('function' === typeof required) && !required.apply(this)) || - self.checkRequired(v, this); + return ((typeof required === 'function') && !required.apply(this)) || + _this.checkRequired(v, this); }; - if ('string' == typeof required) { + if (typeof required === 'string') { message = required; required = undefined; } @@ -553,7 +553,7 @@ SchemaType.prototype.required = function (required, message) { */ SchemaType.prototype.getDefault = function (scope, init) { - var ret = 'function' === typeof this.defaultValue + var ret = typeof this.defaultValue === 'function' ? this.defaultValue.call(scope) : this.defaultValue; @@ -676,7 +676,7 @@ SchemaType.prototype.doValidate = function (value, fn, scope) { } }; - var self = this; + var _this = this; this.validators.forEach(function (v) { if (err) { return; @@ -690,8 +690,8 @@ SchemaType.prototype.doValidate = function (value, fn, scope) { if (validator instanceof RegExp) { validate(validator.test(value), validatorProperties); - } else if ('function' === typeof validator) { - if (value === undefined && !self.isRequired) { + } else if (typeof validator === 'function') { + if (value === undefined && !_this.isRequired) { validate(true, validatorProperties); return; } @@ -740,8 +740,8 @@ SchemaType.prototype.doValidateSync = function (value, scope) { } }; - var self = this; - if (value === undefined && !self.isRequired) { + var _this = this; + if (value === undefined && !_this.isRequired) { return null; } @@ -757,7 +757,7 @@ SchemaType.prototype.doValidateSync = function (value, scope) { if (validator instanceof RegExp) { validate(validator.test(value), validatorProperties); - } else if ('function' === typeof validator) { + } else if (typeof validator === 'function') { // if not async validators if (2 !== validator.length) { validate(validator.call(scope, value), validatorProperties); @@ -797,7 +797,7 @@ SchemaType._isRef = function (self, value, doc, init) { return true; } if (!Buffer.isBuffer(value) && // buffers are objects too - 'Binary' != value._bsontype // raw binary value from the db + 'Binary' !== value._bsontype // raw binary value from the db && utils.isObject(value) // might have deselected _id in population query ) { return true; diff --git a/lib/statemachine.js b/lib/statemachine.js index 217bca4bd37..4bf081b9b3b 100644 --- a/lib/statemachine.js +++ b/lib/statemachine.js @@ -102,10 +102,10 @@ StateMachine.prototype.clear = function clear(state) { */ StateMachine.prototype.some = function some() { - var self = this; + var _this = this; var what = arguments.length ? arguments : this.stateNames; return Array.prototype.some.call(what, function (state) { - return Object.keys(self.states[state]).length; + return Object.keys(_this.states[state]).length; }); }; @@ -126,10 +126,10 @@ StateMachine.prototype._iter = function _iter(iterMethod) { if (!states.length) states = this.stateNames; - var self = this; + var _this = this; var paths = states.reduce(function (paths, state) { - return paths.concat(Object.keys(self.states[state])); + return paths.concat(Object.keys(_this.states[state])); }, []); return paths[iterMethod](function (path, i, paths) { diff --git a/lib/types/array.js b/lib/types/array.js index 21f3e0c1242..cea257cae95 100644 --- a/lib/types/array.js +++ b/lib/types/array.js @@ -106,7 +106,7 @@ MongooseArray.mixin = { populated = owner.populated(this._path, true); } - if (populated && null != value) { + if (populated && null !== value) { // cast to the populated Models schema Model = populated.options.model; @@ -176,7 +176,7 @@ MongooseArray.mixin = { */ _registerAtomic: function (op, val) { - if ('$set' == op) { + if ('$set' === op) { // $set takes precedence over all other ops. // mark entire array modified. this._atomics = {$set: val}; @@ -186,10 +186,10 @@ MongooseArray.mixin = { var atomics = this._atomics; // reset pop/shift after save - if ('$pop' == op && !('$pop' in atomics)) { - var self = this; + if ('$pop' === op && !('$pop' in atomics)) { + var _this = this; this._parent.once('save', function () { - self._popped = self._shifted = null; + _this._popped = _this._shifted = null; }); } @@ -262,7 +262,7 @@ MongooseArray.mixin = { val = val.valueOf(); } - if ('$addToSet' == op) { + if ('$addToSet' === op) { val = {$each: val}; } @@ -282,7 +282,7 @@ MongooseArray.mixin = { */ hasAtomics: function hasAtomics() { - if (!(this._atomics && 'Object' === this._atomics.constructor.name)) { + if (!(this._atomics && this._atomics.constructor.name === 'Object')) { return 0; } diff --git a/lib/types/buffer.js b/lib/types/buffer.js index 8bc6e92b23a..b9f518bf07b 100644 --- a/lib/types/buffer.js +++ b/lib/types/buffer.js @@ -51,7 +51,7 @@ function MongooseBuffer(value, encode, offset) { _parent: {value: doc} }); - if (doc && 'string' === typeof path) { + if (doc && typeof path === 'string') { Object.defineProperty(buf, '_schema', { value: doc.schema.path(path) }); @@ -197,7 +197,7 @@ MongooseBuffer.mixin = { */ MongooseBuffer.mixin.toObject = function (options) { - var subtype = 'number' == typeof options + var subtype = typeof options === 'number' ? options : (this._subtype || 0); return new Binary(this, subtype); @@ -253,11 +253,11 @@ MongooseBuffer.mixin.equals = function (other) { */ MongooseBuffer.mixin.subtype = function (subtype) { - if ('number' != typeof subtype) { + if (typeof subtype !== 'number') { throw new TypeError('Invalid subtype. Expected a number'); } - if (this._subtype != subtype) { + if (this._subtype !== subtype) { this._markModified(); } diff --git a/lib/types/documentarray.js b/lib/types/documentarray.js index f040a4b7c67..8579a87636d 100644 --- a/lib/types/documentarray.js +++ b/lib/types/documentarray.js @@ -209,21 +209,21 @@ MongooseDocumentArray.mixin = { */ notify: function notify(event) { - var self = this; + var _this = this; return function notify(val) { - var i = self.length; + var i = _this.length; while (i--) { - if (!self[i]) continue; + if (!_this[i]) continue; switch (event) { // only swap for save event for now, we may change this to all event types later case 'save': - val = self[i]; + val = _this[i]; break; default: // NO-OP break; } - self[i].emit(event, val); + _this[i].emit(event, val); } }; } diff --git a/lib/types/embedded.js b/lib/types/embedded.js index c0c4f3b4cc0..a243971a91b 100644 --- a/lib/types/embedded.js +++ b/lib/types/embedded.js @@ -29,9 +29,9 @@ function EmbeddedDocument(obj, parentArr, skipId, fields, index) { Document.call(this, obj, fields, skipId); - var self = this; + var _this = this; this.on('isNew', function (val) { - self.isNew = val; + _this.isNew = val; }); } @@ -268,7 +268,7 @@ EmbeddedDocument.prototype.ownerDocument = function () { EmbeddedDocument.prototype.$__fullPath = function (path) { if (!this.$__.fullPath) { - var parent = this; + var parent = this; // eslint-disable-line consistent-this if (!parent.__parent) { return path; } diff --git a/lib/utils.js b/lib/utils.js index 3911723e68a..8ff81acba56 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -151,10 +151,10 @@ exports.deepEqual = function deepEqual(a, b) { } if (a instanceof RegExp && b instanceof RegExp) { - return a.source == b.source && - a.ignoreCase == b.ignoreCase && - a.multiline == b.multiline && - a.global == b.global; + return a.source === b.source && + a.ignoreCase === b.ignoreCase && + a.multiline === b.multiline && + a.global === b.global; } if (typeof a !== 'object' && typeof b !== 'object') { @@ -196,7 +196,7 @@ exports.deepEqual = function deepEqual(a, b) { // having the same number of owned properties (keys incorporates // hasOwnProperty) - if (ka.length != kb.length) { + if (ka.length !== kb.length) { return false; } @@ -206,7 +206,7 @@ exports.deepEqual = function deepEqual(a, b) { // ~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) { + if (ka[i] !== kb[i]) { return false; } } @@ -246,7 +246,7 @@ exports.clone = function clone(obj, options) { } if (isMongooseObject(obj)) { - if (options && options.json && 'function' === typeof obj.toJSON) { + if (options && options.json && typeof obj.toJSON === 'function') { return obj.toJSON(options); } return obj.toObject(options); @@ -299,7 +299,7 @@ function cloneObject(obj, options) { for (k in obj) { val = clone(obj[k], options); - if (!minimize || ('undefined' !== typeof val)) { + if (!minimize || (typeof val !== 'undefined')) { hasKeys || (hasKeys = true); ret[k] = val; } @@ -314,7 +314,7 @@ function cloneObject(obj, options) { k = keys[i]; val = clone(obj[k], options); - if (!minimize || ('undefined' !== typeof val)) { + if (!minimize || (typeof val !== 'undefined')) { if (!hasKeys) { hasKeys = true; } @@ -387,7 +387,7 @@ exports.merge = function merge(to, from) { while (i--) { key = keys[i]; - if ('undefined' === typeof to[key]) { + if (typeof to[key] === 'undefined') { to[key] = from[key]; } else if (exports.isObject(from[key])) { merge(to[key], from[key]); @@ -456,7 +456,7 @@ exports.isObject = function (arg) { if (Buffer.isBuffer(arg)) { return true; } - return '[object Object]' == toString.call(arg); + return '[object Object]' === toString.call(arg); }; /*! @@ -478,7 +478,7 @@ exports.args = sliced; */ exports.tick = function tick(callback) { - if ('function' !== typeof callback) { + if (typeof callback !== 'function') { return; } return function () { @@ -522,7 +522,7 @@ var isMongooseObject = exports.isMongooseObject; */ exports.expires = function expires(object) { - if (!(object && 'Object' == object.constructor.name)) { + if (!(object && object.constructor.name === 'Object')) { return; } if (!('expires' in object)) { @@ -530,7 +530,7 @@ exports.expires = function expires(object) { } var when; - if ('string' != typeof object.expires) { + if (typeof object.expires !== 'string') { when = object.expires; } else { when = Math.round(ms(object.expires) / 1000); @@ -590,13 +590,13 @@ exports.populate = function populate(path, select, model, match, options, subPop subPopulate = path.populate; path = path.path; } - } else if ('string' !== typeof model && 'function' !== typeof model) { + } else if (typeof model !== 'string' && typeof model !== 'function') { options = match; match = model; model = undefined; } - if ('string' != typeof path) { + if (typeof path !== 'string') { throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`'); } @@ -810,7 +810,7 @@ exports.mergeClone = function (to, from) { while (i--) { key = keys[i]; - if ('undefined' === typeof to[key]) { + if (typeof to[key] === 'undefined') { // make sure to retain key order here because of a bug handling the $each // operator in mongodb 2.4.4 to[key] = exports.clone(from[key], {retainKeyOrder: 1}); diff --git a/static.js b/static.js index ade4f661003..f99bf857ec1 100644 --- a/static.js +++ b/static.js @@ -4,7 +4,7 @@ var server = new static.Server('.', {cache: 0}); var open = require('open'); require('http').createServer(function (req, res) { - if ('/favicon.ico' == req.url) { + if ('/favicon.ico' === req.url) { req.destroy(); res.statusCode = 204; return res.end(); diff --git a/test/aggregate.test.js b/test/aggregate.test.js index d252c9f04b0..bb55362b94f 100644 --- a/test/aggregate.test.js +++ b/test/aggregate.test.js @@ -532,7 +532,7 @@ describe('aggregate: ', function () { if (err) { return done(err); } - var mongo26 = 2 < version[0] || (2 == version[0] && 6 <= version[1]); + var mongo26 = version[0] > 2 || (version[0] === 2 && version[1] >= 6); if (!mongo26) { return done(); } @@ -602,7 +602,7 @@ describe('aggregate: ', function () { setupData(function (db) { start.mongodVersion(function (err, version) { if (err) throw err; - var mongo26_or_greater = 2 < version[0] || (2 == version[0] && 6 <= version[1]); + var mongo26_or_greater = version[0] > 2 || (version[0] === 2 && version[1] >= 6); var m = db.model('Employee'); var match = {$match: {sal: {$gt: 15000}}}; diff --git a/test/browser/schema.validation.test_.js b/test/browser/schema.validation.test_.js index 99959a59087..9fde9b2b956 100644 --- a/test/browser/schema.validation.test_.js +++ b/test/browser/schema.validation.test_.js @@ -636,7 +636,7 @@ describe('schema', function () { it('ingore async', function (done) { function syncValidator(val) { - return val == 'sync'; + return val''sync'; } var called = false; @@ -644,7 +644,7 @@ describe('schema', function () { function asyncValidator(val, respond) { called = true; setTimeout(function () { - respond(val == 'async'); + respond(val''async'); }, 0); } @@ -663,7 +663,7 @@ describe('schema', function () { it('subdoc', function (done) { function syncValidator(val) { - return val == 'sync'; + return val === 'sync'; } var called = false; @@ -671,7 +671,7 @@ describe('schema', function () { function asyncValidator(val, respond) { called = true; setTimeout(function () { - respond(val == 'async'); + respond(val === 'async'); }, 0); } diff --git a/test/browser/types.objectid.test_.js b/test/browser/types.objectid.test_.js index 41b284ff529..0fbb1f5b68f 100644 --- a/test/browser/types.objectid.test_.js +++ b/test/browser/types.objectid.test_.js @@ -20,7 +20,7 @@ ObjectId.createFromHexString('00000000000000000000001'); assert.ok(false); } catch (err) { - assert.ok(err != null); + assert.ok(err !== null); } done(); diff --git a/test/connection.test.js b/test/connection.test.js index b619e7269fa..cbdfcead4fd 100644 --- a/test/connection.test.js +++ b/test/connection.test.js @@ -168,7 +168,7 @@ describe('connections:', function () { assert.notEqual(port1, db.port); assert.ok(db1 !== db.db); - assert.ok(db1.serverConfig.port != db.db.serverConfig.port); + assert.ok(db1.serverConfig.port !== db.db.serverConfig.port); var port2 = db.port; var db2 = db.db; @@ -184,7 +184,7 @@ describe('connections:', function () { assert.notEqual(port2, db.port); assert.ok(db2 !== db.db); - assert.ok(db2.serverConfig.port != db.db.serverConfig.port); + assert.ok(db2.serverConfig.port !== db.db.serverConfig.port); db.close(done); }); @@ -711,7 +711,7 @@ describe('connections:', function () { var A = mongoose.model('testing853a', new Schema({x: String}), 'testing853-1'); var B = mongoose.model('testing853b', new Schema({x: String}), 'testing853-2'); var C = B.model('testing853a'); - assert.ok(C == A); + assert.ok(C === A); done(); }); @@ -761,7 +761,7 @@ describe('connections:', function () { var A = mongoose.model('gh-1209-a', s1); var B = db.model('gh-1209-a', s2); - assert.ok(A.schema != B.schema); + assert.ok(A.schema !== B.schema); assert.ok(A.schema.paths.one); assert.ok(B.schema.paths.two); assert.ok(!B.schema.paths.one); @@ -770,7 +770,7 @@ describe('connections:', function () { // reset delete db.models['gh-1209-a']; var C = db.model('gh-1209-a'); - assert.ok(C.schema == A.schema); + assert.ok(C.schema === A.schema); db.close(); done(); @@ -797,10 +797,10 @@ describe('connections:', function () { var A = db.model(name, s1); var B = db.model(name); var C = db.model(name, 'alternate'); - assert.ok(A.collection.name == B.collection.name); - assert.ok(A.collection.name != C.collection.name); - assert.ok(db.models[name].collection.name != C.collection.name); - assert.ok(db.models[name].collection.name == A.collection.name); + assert.ok(A.collection.name === B.collection.name); + assert.ok(A.collection.name !== C.collection.name); + assert.ok(db.models[name].collection.name !== C.collection.name); + assert.ok(db.models[name].collection.name === A.collection.name); db.close(); done(); }); diff --git a/test/document.hooks.test.js b/test/document.hooks.test.js index f287e116942..b27d47a1d6e 100644 --- a/test/document.hooks.test.js +++ b/test/document.hooks.test.js @@ -698,7 +698,7 @@ describe('document: hooks:', function () { describe('gh-3284', function () { it('should call pre hooks on nested subdoc', function (done) { - var self = this; + var _this = this; var childSchema = new Schema({ title: String @@ -706,7 +706,7 @@ describe('document: hooks:', function () { ['init', 'save', 'validate'].forEach(function (type) { childSchema.pre(type, function (next) { - self['pre' + type + 'Called'] = true; + _this['pre' + type + 'Called'] = true; next(); }); }); @@ -734,9 +734,9 @@ describe('document: hooks:', function () { return Parent.findById(parent._id); }).then(function () { db.close(); - assert.ok(self.preinitCalled); - assert.ok(self.prevalidateCalled); - assert.ok(self.presaveCalled); + assert.ok(_this.preinitCalled); + assert.ok(_this.prevalidateCalled); + assert.ok(_this.presaveCalled); done(); }); }); diff --git a/test/document.test.js b/test/document.test.js index cd7f0fd923f..98252dbd6be 100644 --- a/test/document.test.js +++ b/test/document.test.js @@ -346,7 +346,7 @@ describe('document', function () { doc.schema.options.toObject = {}; doc.schema.options.toObject.transform = function xform(doc, ret) { // ignore embedded docs - if ('function' == typeof doc.ownerDocument) { + if ('function' === typeof doc.ownerDocument) { return; } @@ -368,7 +368,7 @@ describe('document', function () { var out = {myid: doc._id.toString()}; doc.schema.options.toObject.transform = function (doc, ret) { // ignore embedded docs - if ('function' == typeof doc.ownerDocument) { + if ('function' === typeof doc.ownerDocument) { return; } @@ -682,7 +682,7 @@ describe('document', function () { doc.schema.options.toJSON = {}; doc.schema.options.toJSON.transform = function xform(doc, ret) { // ignore embedded docs - if ('function' == typeof doc.ownerDocument) { + if ('function' === typeof doc.ownerDocument) { return; } @@ -704,7 +704,7 @@ describe('document', function () { var out = {myid: doc._id.toString()}; doc.schema.options.toJSON.transform = function (doc, ret) { // ignore embedded docs - if ('function' == typeof doc.ownerDocument) { + if ('function' === typeof doc.ownerDocument) { return; } diff --git a/test/index.test.js b/test/index.test.js index d6bcd971dc6..eac4d5e1950 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -221,10 +221,10 @@ describe('mongoose module:', function () { var A = m.model(name, s1); var B = m.model(name); var C = m.model(name, 'alternate'); - assert.ok(A.collection.name == B.collection.name); - assert.ok(A.collection.name != C.collection.name); - assert.ok(m.models[name].collection.name != C.collection.name); - assert.ok(m.models[name].collection.name == A.collection.name); + assert.ok(A.collection.name === B.collection.name); + assert.ok(A.collection.name !== C.collection.name); + assert.ok(m.models[name].collection.name !== C.collection.name); + assert.ok(m.models[name].collection.name === A.collection.name); done(); }); }); diff --git a/test/model.aggregate.test.js b/test/model.aggregate.test.js index ec907413dfe..c895ace9af3 100644 --- a/test/model.aggregate.test.js +++ b/test/model.aggregate.test.js @@ -48,7 +48,7 @@ describe('model aggregate', function () { assert.ifError(err); start.mongodVersion(function (err, version) { if (err) throw err; - mongo26_or_greater = 2 < version[0] || (2 == version[0] && 6 <= version[1]); + mongo26_or_greater = version[0] > 2 || (version[0] === 2 && version[1] >= 6); if (!mongo26_or_greater) console.log('not testing mongodb 2.6 features'); done(); }); diff --git a/test/model.findOneAndUpdate.test.js b/test/model.findOneAndUpdate.test.js index a256fd9c87c..46bde1ac311 100644 --- a/test/model.findOneAndUpdate.test.js +++ b/test/model.findOneAndUpdate.test.js @@ -1195,12 +1195,14 @@ describe('model: findByIdAndUpdate:', function () { var s = new Schema({ topping: { - type: String, validate: function () { + type: String, + validate: function () { return false; } }, base: { - type: String, validate: function () { + type: String, + validate: function () { return true; } } @@ -1222,8 +1224,7 @@ describe('model: findByIdAndUpdate:', function () { assert.ok(!breakfast); assert.equal(1, Object.keys(error.errors).length); assert.equal('topping', Object.keys(error.errors)[0]); - assert.equal('Validator failed for path `topping` with value `bacon`', - error.errors['topping'].message); + assert.equal('Validator failed for path `topping` with value `bacon`', error.errors.topping.message); assert.ok(!breakfast); db.close(); @@ -1253,12 +1254,10 @@ describe('model: findByIdAndUpdate:', function () { assert.ok(!!error); assert.ok(!breakfast); assert.equal(2, Object.keys(error.errors).length); - assert.ok(Object.keys(error.errors).indexOf('eggs') != -1); - assert.ok(Object.keys(error.errors).indexOf('steak') != -1); - assert.equal('Validator failed for path `eggs` with value `softboiled`', - error.errors['eggs'].message); - assert.equal('Path `steak` is required.', - error.errors['steak'].message); + assert.ok(Object.keys(error.errors).indexOf('eggs') !== -1); + assert.ok(Object.keys(error.errors).indexOf('steak') !== -1); + assert.equal('Validator failed for path `eggs` with value `softboiled`', error.errors.eggs.message); + assert.equal('Path `steak` is required.', error.errors.steak.message); db.close(); done(); }); @@ -1283,8 +1282,7 @@ describe('model: findByIdAndUpdate:', function () { assert.ok(!!error); assert.equal(1, Object.keys(error.errors).length); assert.equal('eggs', Object.keys(error.errors)[0]); - assert.equal('Path `eggs` (3) is less than minimum allowed value (4).', - error.errors['eggs'].message); + assert.equal('Path `eggs` (3) is less than minimum allowed value (4).', error.errors.eggs.message); Breakfast.findOneAndUpdate( {}, @@ -1294,9 +1292,7 @@ describe('model: findByIdAndUpdate:', function () { assert.ok(!!error); assert.equal(1, Object.keys(error.errors).length); assert.equal('steak', Object.keys(error.errors)[0]); - assert.equal('`tofu` is not a valid enum value for path `steak`.', - error.errors['steak']); - + assert.equal('`tofu` is not a valid enum value for path `steak`.', error.errors.steak); Breakfast.findOneAndUpdate( {}, @@ -1306,8 +1302,7 @@ describe('model: findByIdAndUpdate:', function () { assert.ok(!!error); assert.equal(1, Object.keys(error.errors).length); assert.equal('bacon', Object.keys(error.errors)[0]); - assert.equal('Path `bacon` is invalid (none).', - error.errors['bacon'].message); + assert.equal('Path `bacon` is invalid (none).', error.errors.bacon.message); db.close(); done(); diff --git a/test/model.geonear.test.js b/test/model.geonear.test.js index d13c5444ecd..0c286b58f16 100644 --- a/test/model.geonear.test.js +++ b/test/model.geonear.test.js @@ -36,7 +36,7 @@ describe('model', function () { before(function (done) { start.mongodVersion(function (err, version) { if (err) throw err; - mongo24_or_greater = 2 < version[0] || (2 == version[0] && 4 <= version[1]); + mongo24_or_greater = version[0] > 2 || (version[0] === 2 && version[1] >= 4); if (!mongo24_or_greater) console.log('not testing mongodb 2.4 features'); done(); }); diff --git a/test/model.hydrate.test.js b/test/model.hydrate.test.js index ae94a6d881a..6d62657fb1e 100644 --- a/test/model.hydrate.test.js +++ b/test/model.hydrate.test.js @@ -67,7 +67,7 @@ describe('model', function () { hydrated.validate(function (err) { assert.ok(err); - assert.ok(err.errors['food']); + assert.ok(err.errors.food); assert.deepEqual(['food'], Object.keys(err.errors)); done(); }); diff --git a/test/model.indexes.test.js b/test/model.indexes.test.js index 7db34644702..4fbca37788b 100644 --- a/test/model.indexes.test.js +++ b/test/model.indexes.test.js @@ -72,13 +72,13 @@ describe('model', function () { for (var i in indexes) { indexes[i].forEach(function (index) { - if (index[0] == 'name') { + if (index[0] === 'name') { assertions++; } - if (index[0] == 'blogposts._id') { + if (index[0] === 'blogposts._id') { assertions++; } - if (index[0] == 'blogposts.title') { + if (index[0] === 'blogposts.title') { assertions++; } }); diff --git a/test/model.mapreduce.test.js b/test/model.mapreduce.test.js index 6b04f901e63..9dcd240c7bb 100644 --- a/test/model.mapreduce.test.js +++ b/test/model.mapreduce.test.js @@ -79,16 +79,16 @@ describe('model: mapreduce:', function () { assert.ok(Array.isArray(ret)); assert.ok(stats); ret.forEach(function (res) { - if ('aaron' == res._id) { + if (res._id === 'aaron') { assert.equal(3, res.value); } - if ('guillermo' == res._id) { + if (res._id === 'guillermo') { assert.equal(3, res.value); } - if ('brian' == res._id) { + if (res._id === 'brian') { assert.equal(2, res.value); } - if ('nathan' == res._id) { + if (res._id === 'nathan') { assert.equal(2, res.value); } }); @@ -275,16 +275,16 @@ describe('model: mapreduce:', function () { assert.ok(Array.isArray(ret)); assert.ok(stats); ret.forEach(function (res) { - if ('aaron' == res._id) { + if (res._id === 'aaron') { assert.equal(6, res.value); } - if ('guillermo' == res._id) { + if (res._id === 'guillermo') { assert.equal(6, res.value); } - if ('brian' == res._id) { + if (res._id === 'brian') { assert.equal(4, res.value); } - if ('nathan' == res._id) { + if (res._id === 'nathan') { assert.equal(4, res.value); } }); diff --git a/test/model.middleware.test.js b/test/model.middleware.test.js index fdbadd45ee6..c949554f619 100644 --- a/test/model.middleware.test.js +++ b/test/model.middleware.test.js @@ -205,16 +205,16 @@ describe('model middleware', function () { parent.save(function (error) { assert.ifError(error); assert.equal(2, childPreCalls); - assert.equal(1, childPreCallsByName['Jaina']); - assert.equal(1, childPreCallsByName['Jacen']); + assert.equal(1, childPreCallsByName.Jaina); + assert.equal(1, childPreCallsByName.Jacen); assert.equal(1, parentPreCalls); parent.children[0].name = 'Anakin'; parent.save(function (error) { assert.ifError(error); assert.equal(4, childPreCalls); - assert.equal(1, childPreCallsByName['Anakin']); - assert.equal(1, childPreCallsByName['Jaina']); - assert.equal(2, childPreCallsByName['Jacen']); + assert.equal(1, childPreCallsByName.Anakin); + assert.equal(1, childPreCallsByName.Jaina); + assert.equal(2, childPreCallsByName.Jacen); assert.equal(2, parentPreCalls); db.close(); diff --git a/test/model.populate.test.js b/test/model.populate.test.js index f10512fc9ac..a911b83051c 100644 --- a/test/model.populate.test.js +++ b/test/model.populate.test.js @@ -297,7 +297,7 @@ describe('model: populate:', function () { db.close(); db2.close(); assert.ifError(err); - assert.ok(post._creator.name == 'Guillermo'); + assert.ok(post._creator.name === 'Guillermo'); done(); }); }); @@ -327,7 +327,7 @@ describe('model: populate:', function () { // mock an error User.find = function () { var args = Array.prototype.map.call(arguments, function (arg) { - return 'function' == typeof arg ? function () { + return 'function' === typeof arg ? function () { arg(new Error('woot')); } : arg; }); @@ -653,7 +653,7 @@ describe('model: populate:', function () { var origFind = User.find; User.find = function () { var args = Array.prototype.map.call(arguments, function (arg) { - return 'function' == typeof arg ? function () { + return 'function' === typeof arg ? function () { arg(new Error('woot 2')); } : arg; }); @@ -2758,7 +2758,7 @@ describe('model: populate:', function () { docs.forEach(function (doc) { assert.ok(doc.comment && doc.comment.body); - if ('u1' == doc.name) { + if (doc.name === 'u1') { assert.equal('comment 1', doc.comment.body); } else { assert.equal('comment 2', doc.comment.body); @@ -2802,7 +2802,7 @@ describe('model: populate:', function () { assert.ifError(err); var a2 = docs.filter(function (d) { - return 'body2' == d.body; + return d.body === 'body2'; })[0]; assert.equal(a2.mediaAttach.id, media.id); diff --git a/test/model.querying.test.js b/test/model.querying.test.js index d97fcf97504..8e85d25949a 100644 --- a/test/model.querying.test.js +++ b/test/model.querying.test.js @@ -62,7 +62,7 @@ describe('model: querying:', function () { if (err) { throw err; } - mongo26_or_greater = 2 < version[0] || (2 == version[0] && 6 <= version[1]); + mongo26_or_greater = version[0] > 2 || (version[0] === 2 && version[1] >= 6); if (!mongo26_or_greater) { console.log('not testing mongodb 2.6 features'); } @@ -1143,9 +1143,9 @@ describe('model: querying:', function () { var found2 = false; found.forEach(function (doc) { - if (doc.id == one.id) { + if (doc.id === one.id) { found1 = true; - } else if (doc.id == two.id) { + } else if (doc.id === two.id) { found2 = true; } }); @@ -1174,9 +1174,9 @@ describe('model: querying:', function () { var found2 = false; found.forEach(function (doc) { - if (doc.id == one.id) { + if (doc.id === one.id) { found1 = true; - } else if (doc.id == two.id) { + } else if (doc.id === two.id) { found2 = true; } }); @@ -1519,7 +1519,7 @@ describe('model: querying:', function () { assert.equal(docs[1].dt, '2011-03-31'); assert.equal(docs[2].dt, '2011-04-01'); assert.equal(false, docs.some(function (d) { - return '2011-04-02' === d.dt; + return d.dt === '2011-04-02'; })); }); @@ -1533,10 +1533,10 @@ describe('model: querying:', function () { assert.equal(docs[0].dt, '2011-03-31'); assert.equal(docs[1].dt, '2011-04-01'); assert.equal(false, docs.some(function (d) { - return '2011-03-30' === d.dt; + return d.dt === '2011-03-30'; })); assert.equal(false, docs.some(function (d) { - return '2011-04-02' === d.dt; + return d.dt === '2011-04-02'; })); }); } @@ -1851,7 +1851,7 @@ describe('model: querying:', function () { if (err) { throw err; } - var mongo26_or_greater = 2 < version[0] || (2 == version[0] && 6 <= version[1]); + var mongo26_or_greater = version[0] > 2 || (version[0] === 2 && version[1] >= 6); if (!mongo26_or_greater) { return done(); } @@ -2316,7 +2316,7 @@ describe('geo-spatial', function () { throw err; } - mongo24_or_greater = 2 < version[0] || (2 == version[0] && 4 <= version[1]); + mongo24_or_greater = version[0] > 2 || (version[0] === 2 && version[1] >= 4); if (!mongo24_or_greater) { console.log('not testing mongodb 2.4 features'); } @@ -2330,7 +2330,7 @@ describe('geo-spatial', function () { } var ok = schema2dsphere.indexes().some(function (index) { - return '2dsphere' == index[0].loc; + return index[0].loc === '2dsphere'; }); assert.ok(ok); done(); @@ -2552,7 +2552,7 @@ describe('geo-spatial', function () { if (err) { return done(err); } - mongo24_or_greater = 2 < version[0] || (2 == version[0] && 4 <= version[1]); + mongo24_or_greater = version[0] > 2 || (version[0] === 2 && version[1] >= 4); if (!mongo24_or_greater) { console.log('not testing mongodb 2.4 features'); } @@ -2580,7 +2580,7 @@ describe('geo-spatial', function () { assert.ifError(err); var found = indexes.some(function (index) { - return 'hashed' === index.key.t; + return index.key.t === 'hashed'; }); assert.ok(found); @@ -2595,7 +2595,7 @@ describe('geo-spatial', function () { }); function complete() { - if (0 === --pending) { + if (--pending === 0) { db.close(done); } } @@ -2713,7 +2713,7 @@ describe('lean option:', function () { if (err) { return done(err); } - mongo26 = 2 < version[0] || (2 == version[0] && 6 <= version[1]); + mongo26 = version[0] > 2 || (version[0] === 2 && version[1] >= 6); done(); }); }); diff --git a/test/model.stream.test.js b/test/model.stream.test.js index aa2780630ba..a407bef2e5b 100644 --- a/test/model.stream.test.js +++ b/test/model.stream.test.js @@ -52,6 +52,17 @@ describe('query stream:', function () { var stream = P.find().batchSize(3).stream(); + function cb() { + db.close(); + assert.strictEqual(undefined, err); + assert.equal(i, names.length); + assert.equal(1, closed); + assert.equal(1, paused); + assert.equal(1, resumed); + assert.equal(true, stream._cursor.isClosed()); + done(); + } + stream.on('data', function (doc) { assert.strictEqual(true, !!doc.name); assert.strictEqual(true, !!doc._id); @@ -96,17 +107,6 @@ describe('query stream:', function () { closed++; cb(); }); - - function cb() { - db.close(); - assert.strictEqual(undefined, err); - assert.equal(i, names.length); - assert.equal(1, closed); - assert.equal(1, paused); - assert.equal(1, resumed); - assert.equal(true, stream._cursor.isClosed()); - done(); - } }); it('immediately destroying a stream prevents the query from executing', function (done) { @@ -116,14 +116,6 @@ describe('query stream:', function () { var stream = P.where('name', 'Jonah').select('name').findOne().stream(); - stream.on('data', function () { - i++; - }); - stream.on('close', cb); - stream.on('error', cb); - - stream.destroy(); - function cb(err) { assert.ifError(err); assert.equal(0, i); @@ -133,6 +125,14 @@ describe('query stream:', function () { done(); }); } + + stream.on('data', function () { + i++; + }); + stream.on('close', cb); + stream.on('error', cb); + + stream.destroy(); }); it('destroying a stream stops it', function (done) { @@ -148,17 +148,6 @@ describe('query stream:', function () { assert.strictEqual(null, stream._destroyed); assert.equal(true, stream.readable); - stream.on('data', function (doc) { - assert.strictEqual(undefined, doc.name); - if (++i === 5) { - stream.destroy(); - assert.equal(false, stream.readable); - } - }); - - stream.on('close', cb); - stream.on('error', cb); - function cb(err) { ++finished; setTimeout(function () { @@ -172,6 +161,17 @@ describe('query stream:', function () { done(); }, 100); } + + stream.on('data', function (doc) { + assert.strictEqual(undefined, doc.name); + if (++i === 5) { + stream.destroy(); + assert.equal(false, stream.readable); + } + }); + + stream.on('close', cb); + stream.on('error', cb); }); it('errors', function (done) { @@ -185,18 +185,6 @@ describe('query stream:', function () { var stream = P.find().batchSize(5).stream(); - stream.on('data', function () { - if (++i === 5) { - db.close(); - } - }); - - stream.on('close', function () { - closed++; - }); - - stream.on('error', cb); - function cb(err) { ++finished; setTimeout(function () { @@ -210,6 +198,18 @@ describe('query stream:', function () { done(); }, 100); } + + stream.on('data', function () { + if (++i === 5) { + db.close(); + } + }); + + stream.on('close', function () { + closed++; + }); + + stream.on('error', cb); }); it('pipe', function (done) { @@ -222,7 +222,7 @@ describe('query stream:', function () { var stream = P.find().sort('name').limit(20).stream(opts); stream.pipe(out); - var cb = function (err) { + function cb(err) { db.close(); assert.ifError(err); var contents = fs.readFileSync(filename, 'utf8'); @@ -233,7 +233,7 @@ describe('query stream:', function () { assert.ok(/Agustin/.test(contents)); fs.unlink(filename); done(); - }; + } stream.on('error', cb); out.on('close', cb); @@ -248,6 +248,15 @@ describe('query stream:', function () { var stream = P.find({}).lean().stream(); + function cb() { + db.close(); + assert.strictEqual(undefined, err); + assert.equal(i, names.length); + assert.equal(1, closed); + assert.equal(true, stream._cursor.isClosed()); + done(); + } + stream.on('data', function (doc) { assert.strictEqual(false, doc instanceof mongoose.Document); i++; @@ -277,15 +286,6 @@ describe('query stream:', function () { closed++; cb(); }); - - var cb = function () { - db.close(); - assert.strictEqual(undefined, err); - assert.equal(i, names.length); - assert.equal(1, closed); - assert.equal(true, stream._cursor.isClosed()); - done(); - }; }); it('supports $elemMatch with $in (gh-1091)', function (done) { @@ -342,6 +342,14 @@ describe('query stream:', function () { var Bar = db.model('Bar', barSchema); var found = []; + function complete(err) { + if (!err) { + assert.ok(~found.indexOf(2)); + assert.ok(~found.indexOf(3)); + } + db.close(done); + } + Bar.create({value: 2}, {value: 3}, function (err, bar1, bar2) { if (err) return complete(err); @@ -359,14 +367,6 @@ describe('query stream:', function () { on('error', complete); }); }); - - var complete = function (err) { - if (!err) { - assert.ok(~found.indexOf(2)); - assert.ok(~found.indexOf(3)); - } - db.close(done); - }; }); it('respects schema options (gh-1862)', function (done) { diff --git a/test/model.test.js b/test/model.test.js index b7ab7ebd05f..a4f6c3df5da 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -782,8 +782,9 @@ describe('Model', function () { BlogPost = db.model('BlogPost', collection), threw = false; + var post; try { - var post = new BlogPost({date: 'Test', meta: {date: 'Test'}}); + post = new BlogPost({date: 'Test', meta: {date: 'Test'}}); } catch (e) { threw = true; } @@ -1542,7 +1543,7 @@ describe('Model', function () { }); ValidationMiddlewareSchema.pre('validate', function (next) { - if (this.get('baz') == 'bad') { + if (this.get('baz') === 'bad') { this.invalidate('baz', 'bad'); } next(); @@ -1580,10 +1581,10 @@ describe('Model', function () { }); AsyncValidationMiddlewareSchema.pre('validate', true, function (next, done) { - var self = this; + var _this = this; setTimeout(function () { - if (self.get('prop') == 'bad') { - self.invalidate('prop', 'bad'); + if (_this.get('prop') === 'bad') { + _this.invalidate('prop', 'bad'); } done(); }, 5); @@ -1628,10 +1629,10 @@ describe('Model', function () { }); ComplexValidationMiddlewareSchema.pre('validate', true, function (next, done) { - var self = this; + var _this = this; setTimeout(function () { - if (self.get('baz') == 'bad') { - self.invalidate('baz', 'bad'); + if (_this.get('baz') === 'bad') { + _this.invalidate('baz', 'bad'); } done(); }, 5); @@ -2532,6 +2533,58 @@ describe('Model', function () { var post = new BlogPost; + function complete() { + BlogPost.findOne({_id: post.get('_id')}, function (err, doc) { + db.close(); + + assert.ifError(err); + assert.equal(doc.get('comments').length, 5); + + var v = doc.get('comments').some(function (comment) { + return comment.get('title') === '1'; + }); + + assert.ok(v); + + v = doc.get('comments').some(function (comment) { + return comment.get('title') === '2'; + }); + + assert.ok(v); + + v = doc.get('comments').some(function (comment) { + return comment.get('title') === '3'; + }); + + assert.ok(v); + + v = doc.get('comments').some(function (comment) { + return comment.get('title') === '4'; + }); + + assert.ok(v); + + v = doc.get('comments').some(function (comment) { + return comment.get('title') === '5'; + }); + + assert.ok(v); + done(); + }); + } + + function save(doc) { + saveQueue.push(doc); + if (saveQueue.length === 4) { + saveQueue.forEach(function (doc) { + doc.save(function (err) { + assert.ifError(err); + --totalDocs || complete(); + }); + }); + } + } + post.save(function (err) { assert.ifError(err); @@ -2558,58 +2611,6 @@ describe('Model', function () { doc.get('comments').push({title: '4'}, {title: '5'}); save(doc); }); - - function save(doc) { - saveQueue.push(doc); - if (saveQueue.length == 4) { - saveQueue.forEach(function (doc) { - doc.save(function (err) { - assert.ifError(err); - --totalDocs || complete(); - }); - }); - } - } - - function complete() { - BlogPost.findOne({_id: post.get('_id')}, function (err, doc) { - db.close(); - - assert.ifError(err); - assert.equal(doc.get('comments').length, 5); - - var v = doc.get('comments').some(function (comment) { - return comment.get('title') == '1'; - }); - - assert.ok(v); - - v = doc.get('comments').some(function (comment) { - return comment.get('title') == '2'; - }); - - assert.ok(v); - - v = doc.get('comments').some(function (comment) { - return comment.get('title') == '3'; - }); - - assert.ok(v); - - v = doc.get('comments').some(function (comment) { - return comment.get('title') == '4'; - }); - - assert.ok(v); - - v = doc.get('comments').some(function (comment) { - return comment.get('title') == '5'; - }); - - assert.ok(v); - done(); - }); - } }); }); @@ -2870,6 +2871,41 @@ describe('Model', function () { var t = new Temp(); + function complete() { + Temp.findOne({_id: t.get('_id')}, function (err, doc) { + assert.ifError(err); + assert.equal(3, doc.get('nums').length); + + var v = doc.get('nums').some(function (num) { + return num.valueOf() === 1; + }); + assert.ok(v); + + v = doc.get('nums').some(function (num) { + return num.valueOf() === 2; + }); + assert.ok(v); + + v = doc.get('nums').some(function (num) { + return num.valueOf() === 3; + }); + assert.ok(v); + db.close(done); + }); + } + + function save(doc) { + saveQueue.push(doc); + if (saveQueue.length === totalDocs) { + saveQueue.forEach(function (doc) { + doc.save(function (err) { + assert.ifError(err); + --totalDocs || complete(); + }); + }); + } + } + t.save(function (err) { assert.ifError(err); @@ -2884,41 +2920,6 @@ describe('Model', function () { doc.get('nums').push(2, 3); save(doc); }); - - function save(doc) { - saveQueue.push(doc); - if (saveQueue.length == totalDocs) { - saveQueue.forEach(function (doc) { - doc.save(function (err) { - assert.ifError(err); - --totalDocs || complete(); - }); - }); - } - } - - function complete() { - Temp.findOne({_id: t.get('_id')}, function (err, doc) { - assert.ifError(err); - assert.equal(3, doc.get('nums').length); - - var v = doc.get('nums').some(function (num) { - return num.valueOf() == '1'; - }); - assert.ok(v); - - v = doc.get('nums').some(function (num) { - return num.valueOf() == '2'; - }); - assert.ok(v); - - v = doc.get('nums').some(function (num) { - return num.valueOf() == '3'; - }); - assert.ok(v); - db.close(done); - }); - } }); }); @@ -2935,6 +2936,43 @@ describe('Model', function () { var t = new StrList(); + function complete() { + StrList.findOne({_id: t.get('_id')}, function (err, doc) { + db.close(); + assert.ifError(err); + + assert.equal(3, doc.get('strings').length); + + var v = doc.get('strings').some(function (str) { + return str === 'a'; + }); + assert.ok(v); + + v = doc.get('strings').some(function (str) { + return str === 'b'; + }); + assert.ok(v); + + v = doc.get('strings').some(function (str) { + return str === 'c'; + }); + assert.ok(v); + done(); + }); + } + + function save(doc) { + saveQueue.push(doc); + if (saveQueue.length === totalDocs) { + saveQueue.forEach(function (doc) { + doc.save(function (err) { + assert.ifError(err); + --totalDocs || complete(); + }); + }); + } + } + t.save(function (err) { assert.ifError(err); @@ -2949,44 +2987,6 @@ describe('Model', function () { doc.get('strings').push('b', 'c'); save(doc); }); - - - function save(doc) { - saveQueue.push(doc); - if (saveQueue.length == totalDocs) { - saveQueue.forEach(function (doc) { - doc.save(function (err) { - assert.ifError(err); - --totalDocs || complete(); - }); - }); - } - } - - function complete() { - StrList.findOne({_id: t.get('_id')}, function (err, doc) { - db.close(); - assert.ifError(err); - - assert.equal(3, doc.get('strings').length); - - var v = doc.get('strings').some(function (str) { - return str == 'a'; - }); - assert.ok(v); - - v = doc.get('strings').some(function (str) { - return str == 'b'; - }); - assert.ok(v); - - v = doc.get('strings').some(function (str) { - return str == 'c'; - }); - assert.ok(v); - done(); - }); - } }); }); @@ -3003,6 +3003,44 @@ describe('Model', function () { var t = new BufList(); + function complete() { + BufList.findOne({_id: t.get('_id')}, function (err, doc) { + db.close(); + assert.ifError(err); + + assert.equal(3, doc.get('buffers').length); + + var v = doc.get('buffers').some(function (buf) { + return buf[0] === 140; + }); + assert.ok(v); + + v = doc.get('buffers').some(function (buf) { + return buf[0] === 141; + }); + assert.ok(v); + + v = doc.get('buffers').some(function (buf) { + return buf[0] === 142; + }); + assert.ok(v); + + done(); + }); + } + + function save(doc) { + saveQueue.push(doc); + if (saveQueue.length === totalDocs) { + saveQueue.forEach(function (doc) { + doc.save(function (err) { + assert.ifError(err); + --totalDocs || complete(); + }); + }); + } + } + t.save(function (err) { assert.ifError(err); @@ -3017,44 +3055,6 @@ describe('Model', function () { doc.get('buffers').push(new Buffer([141]), new Buffer([142])); save(doc); }); - - function save(doc) { - saveQueue.push(doc); - if (saveQueue.length == totalDocs) { - saveQueue.forEach(function (doc) { - doc.save(function (err) { - assert.ifError(err); - --totalDocs || complete(); - }); - }); - } - } - - function complete() { - BufList.findOne({_id: t.get('_id')}, function (err, doc) { - db.close(); - assert.ifError(err); - - assert.equal(3, doc.get('buffers').length); - - var v = doc.get('buffers').some(function (buf) { - return buf[0] == 140; - }); - assert.ok(v); - - v = doc.get('buffers').some(function (buf) { - return buf[0] == 141; - }); - assert.ok(v); - - v = doc.get('buffers').some(function (buf) { - return buf[0] == 142; - }); - assert.ok(v); - - done(); - }); - } }); }); diff --git a/test/model.update.test.js b/test/model.update.test.js index 61a2fdead47..e44cf15966e 100644 --- a/test/model.update.test.js +++ b/test/model.update.test.js @@ -549,9 +549,17 @@ describe('model: update:', function () { var post = new BlogPost; post.set('meta.visitors', 5); + function complete() { + BlogPost.findOne({_id: post.get('_id')}, function (err, doc) { + db.close(); + assert.ifError(err); + assert.equal(9, doc.get('meta.visitors')); + done(); + }); + } + post.save(function (err) { assert.ifError(err); - for (var i = 0; i < 4; ++i) { BlogPost .update({_id: post._id}, {$inc: {'meta.visitors': 1}}, function (err) { @@ -559,15 +567,6 @@ describe('model: update:', function () { --totalDocs || complete(); }); } - - function complete() { - BlogPost.findOne({_id: post.get('_id')}, function (err, doc) { - db.close(); - assert.ifError(err); - assert.equal(9, doc.get('meta.visitors')); - done(); - }); - } }); }); @@ -784,7 +783,7 @@ describe('model: update:', function () { before(function (done) { start.mongodVersion(function (err, version) { assert.ifError(err); - mongo24_or_greater = 2 < version[0] || (2 == version[0] && 4 <= version[1]); + mongo24_or_greater = version[0] > 2 || (version[0] === 2 && version[1] >= 4); done(); }); }); @@ -882,7 +881,7 @@ describe('model: update:', function () { before(function (done) { start.mongodVersion(function (err, version) { assert.ifError(err); - mongo26_or_greater = 2 < version[0] || (2 == version[0] && 6 <= version[1]); + mongo26_or_greater = version[0] > 2 || (version[0] === 2 && version[1] >= 6); done(); }); }); @@ -1102,12 +1101,14 @@ describe('model: update:', function () { var s = new Schema({ topping: { - type: String, validate: function () { + type: String, + validate: function () { return false; } }, base: { - type: String, validate: function () { + type: String, + validate: function () { return true; } } @@ -1119,8 +1120,7 @@ describe('model: update:', function () { assert.ok(!!error); assert.equal(1, Object.keys(error.errors).length); assert.equal('topping', Object.keys(error.errors)[0]); - assert.equal('Validator failed for path `topping` with value `bacon`', - error.errors['topping'].message); + assert.equal('Validator failed for path `topping` with value `bacon`', error.errors.topping.message); Breakfast.findOne({}, function (error, breakfast) { assert.ifError(error); @@ -1152,10 +1152,8 @@ describe('model: update:', function () { assert.equal(2, Object.keys(error.errors).length); assert.ok(Object.keys(error.errors).indexOf('eggs') !== -1); assert.ok(Object.keys(error.errors).indexOf('steak') !== -1); - assert.equal('Validator failed for path `eggs` with value `softboiled`', - error.errors['eggs'].message); - assert.equal('Path `steak` is required.', - error.errors['steak'].message); + assert.equal('Validator failed for path `eggs` with value `softboiled`', error.errors.eggs.message); + assert.equal('Path `steak` is required.', error.errors.steak.message); db.close(); done(); }); @@ -1176,23 +1174,19 @@ describe('model: update:', function () { assert.ok(!!error); assert.equal(1, Object.keys(error.errors).length); assert.equal('eggs', Object.keys(error.errors)[0]); - assert.equal('Path `eggs` (3) is less than minimum allowed value (4).', - error.errors['eggs'].message); + assert.equal('Path `eggs` (3) is less than minimum allowed value (4).', error.errors.eggs.message); Breakfast.update({}, {$set: {steak: 'tofu', eggs: 5, bacon: '3 strips'}}, updateOptions, function (error) { assert.ok(!!error); assert.equal(1, Object.keys(error.errors).length); assert.equal('steak', Object.keys(error.errors)[0]); - assert.equal('`tofu` is not a valid enum value for path `steak`.', - error.errors['steak']); - + assert.equal('`tofu` is not a valid enum value for path `steak`.', error.errors.steak); Breakfast.update({}, {$set: {steak: 'sirloin', eggs: 6, bacon: 'none'}}, updateOptions, function (error) { assert.ok(!!error); assert.equal(1, Object.keys(error.errors).length); assert.equal('bacon', Object.keys(error.errors)[0]); - assert.equal('Path `bacon` is invalid (none).', - error.errors['bacon'].message); + assert.equal('Path `bacon` is invalid (none).', error.errors.bacon.message); db.close(); done(); diff --git a/test/promise.test.js b/test/promise.test.js index 2e7130714bc..7e9a2e3e36e 100644 --- a/test/promise.test.js +++ b/test/promise.test.js @@ -214,7 +214,7 @@ describe('Promise', function () { it('doesnt swallow exceptions (gh-3222)', function (done) { assert.throws(function () { new Promise.ES6(function () { - throw 'bacon'; + throw new Error('bacon'); }); }); done(); diff --git a/test/promise_provider.test.js b/test/promise_provider.test.js index 7ac9ccde3cb..6469a724490 100644 --- a/test/promise_provider.test.js +++ b/test/promise_provider.test.js @@ -80,7 +80,7 @@ describe('ES6 promises: ', function () { }). catch(function (err) { assert.ok(err); - assert.ok(err.errors['test']); + assert.ok(err.errors.test); done(); }); }); @@ -127,7 +127,7 @@ describe('ES6 promises: ', function () { }). catch(function (err) { assert.ok(err); - assert.ok(err.errors['test']); + assert.ok(err.errors.test); done(); }); }); @@ -216,7 +216,7 @@ describe('ES6 promises: ', function () { }). catch(function (err) { assert.ok(err); - assert.ok(err.errors['test']); + assert.ok(err.errors.test); done(); }); }); @@ -263,7 +263,7 @@ describe('ES6 promises: ', function () { }). catch(function (err) { assert.ok(err); - assert.ok(err.errors['test']); + assert.ok(err.errors.test); done(); }); }); @@ -394,7 +394,7 @@ describe('ES6 promises: ', function () { }). catch(function (err) { assert.ok(err); - assert.ok(err.errors['test']); + assert.ok(err.errors.test); done(); }); }); @@ -441,7 +441,7 @@ describe('ES6 promises: ', function () { }). catch(function (err) { assert.ok(err); - assert.ok(err.errors['test']); + assert.ok(err.errors.test); done(); }); }); diff --git a/test/query.test.js b/test/query.test.js index b67595ef1e4..4f82e63543d 100644 --- a/test/query.test.js +++ b/test/query.test.js @@ -425,7 +425,7 @@ describe('Query', function () { var match = {gps: {$within: {$box: [[5, 25], [10, 30]]}}}; if (Query.use$geoWithin) { match.gps.$geoWithin = match.gps.$within; - delete match.gps['$within']; + delete match.gps.$within; } assert.deepEqual(query._conditions, match); done(); @@ -436,7 +436,7 @@ describe('Query', function () { var match = {gps: {$within: {$box: [[5, 25], [10, 30]]}}}; if (Query.use$geoWithin) { match.gps.$geoWithin = match.gps.$within; - delete match.gps['$within']; + delete match.gps.$within; } assert.deepEqual(query._conditions, match); done(); @@ -450,7 +450,7 @@ describe('Query', function () { var match = {gps: {$within: {$center: [[5, 25], 5]}}}; if (Query.use$geoWithin) { match.gps.$geoWithin = match.gps.$within; - delete match.gps['$within']; + delete match.gps.$within; } assert.deepEqual(query._conditions, match); done(); @@ -464,7 +464,7 @@ describe('Query', function () { var match = {gps: {$within: {$centerSphere: [[5, 25], 5]}}}; if (Query.use$geoWithin) { match.gps.$geoWithin = match.gps.$within; - delete match.gps['$within']; + delete match.gps.$within; } assert.deepEqual(query._conditions, match); done(); @@ -478,7 +478,7 @@ describe('Query', function () { var match = {gps: {$within: {$polygon: [{a: {x: 10, y: 20}, b: {x: 15, y: 25}, c: {x: 20, y: 20}}]}}}; if (Query.use$geoWithin) { match.gps.$geoWithin = match.gps.$within; - delete match.gps['$within']; + delete match.gps.$within; } assert.deepEqual(query._conditions, match); done(); @@ -842,7 +842,7 @@ describe('Query', function () { assert.equal(2, Object.keys(q._mongooseOptions.populate).length); assert.deepEqual(o, q._mongooseOptions.populate['yellow.brick']); o.path = 'dirt'; - assert.deepEqual(o, q._mongooseOptions.populate['dirt']); + assert.deepEqual(o, q._mongooseOptions.populate.dirt); done(); }); }); diff --git a/test/schema.select.test.js b/test/schema.select.test.js index e2a532e0b03..e6e44aff89c 100644 --- a/test/schema.select.test.js +++ b/test/schema.select.test.js @@ -43,7 +43,7 @@ describe('schema select option', function () { if (pending === 1) { S.findOneAndRemove({_id: item._id}, cb); } - if (0 === pending) { + if (pending === 0) { done(); } } @@ -84,7 +84,7 @@ describe('schema select option', function () { assert.strictEqual(true, s.isSelected('docs.name')); assert.equal(s.name, 'the included'); - if (0 === pending) { + if (pending === 0) { done(); } } diff --git a/test/schema.test.js b/test/schema.test.js index dbd50a355ff..48949d55fbc 100644 --- a/test/schema.test.js +++ b/test/schema.test.js @@ -1505,7 +1505,7 @@ describe('schema', function () { var band = new Band({name: "Guns N' Roses"}); assert.ok(band.validateSync()); - assert.ok(band.validateSync().errors['guitarist']); + assert.ok(band.validateSync().errors.guitarist); band.guitarist = {name: 'Slash'}; assert.ifError(band.validateSync()); diff --git a/test/schema.timestamps.test.js b/test/schema.timestamps.test.js index eeb5fcd01a4..67f4176a8f1 100644 --- a/test/schema.timestamps.test.js +++ b/test/schema.timestamps.test.js @@ -70,7 +70,7 @@ describe('schema options.timestamps', function () { cat.save(function (err, doc) { assert.ok(doc.createdAt); assert.ok(doc.updatedAt); - assert.ok(doc.createdAt.getTime() == doc.updatedAt.getTime()); + assert.ok(doc.createdAt.getTime() === doc.updatedAt.getTime()); done(); }); }); @@ -79,7 +79,7 @@ describe('schema options.timestamps', function () { Cat.findOneAndUpdate({name: 'notexistname'}, {$set: {}}, {upsert: true, 'new': true}, function (err, doc) { assert.ok(doc.createdAt); assert.ok(doc.updatedAt); - assert.ok(doc.createdAt.getTime() == doc.updatedAt.getTime()); + assert.ok(doc.createdAt.getTime() === doc.updatedAt.getTime()); done(); }); }); diff --git a/test/schema.validation.test.js b/test/schema.validation.test.js index b8334605a56..589e4e84143 100644 --- a/test/schema.validation.test.js +++ b/test/schema.validation.test.js @@ -86,7 +86,7 @@ describe('schema', function () { Test.path('state').doValidate('x', function (err) { assert.ok(err instanceof ValidatorError); assert.equal(err.message, - 'enum validator failed for path `state`: test'); + 'enum validator failed for path `state`: test'); }); Test.path('state').doValidate('opening', function (err) { @@ -447,7 +447,9 @@ describe('schema', function () { setTimeout(function () { executed++; fn(value === true); - if (2 === executed) done(); + if (executed == 2) { + done(); + } }, 5); } @@ -471,23 +473,22 @@ describe('schema', function () { setTimeout(function () { executed++; fn(value === true); - if (2 === executed) done(); + if (executed === 2) { + done(); + } }, 5); } var Animal = new Schema({ ferret: { type: Boolean, - validate: [ - { - 'validator': validator, - 'msg': 'validator1' - }, - { - 'validator': validator, - 'msg': 'validator2' - } - ] + validate: [{ + validator: validator, + msg: 'validator1' + }, { + validator: validator, + msg: 'validator2' + }] } }); @@ -520,16 +521,13 @@ describe('schema', function () { var Animal = new Schema({ ferret: { type: Boolean, - validate: [ - { - 'validator': validator1, - 'msg': 'validator1' - }, - { - 'validator': validator2, - 'msg': 'validator2' - } - ] + validate: [{ + validator: validator1, + msg: 'validator1' + }, { + validator: validator2, + msg: 'validator2' + }] } }); @@ -540,6 +538,7 @@ describe('schema', function () { it('scope', function (done) { var called = false; + function validator(value, fn) { assert.equal('b', this.a); @@ -634,7 +633,9 @@ describe('schema', function () { x: { type: String, validate: [{ - validator: function () { return false; }, + validator: function () { + return false; + }, msg: 'Error code {ERRORCODE}', errorCode: 25 }] @@ -655,7 +656,9 @@ describe('schema', function () { x: { type: String, validate: [{ - validator: function (value, fn) { fn(false, 'Custom message'); }, + validator: function (value, fn) { + fn(false, 'Custom message'); + }, msg: 'Does not matter' }] } @@ -677,6 +680,7 @@ describe('schema', function () { function validate() { return false; } + var validator = [validate, '{PATH} failed validation ({VALUE})', 'customType']; var schema = new Schema({x: {type: [], validate: validator}}); @@ -695,8 +699,9 @@ describe('schema', function () { function validate() { return false; } + var validator = [ - {validator: validate, msg: '{PATH} failed validation ({VALUE})', type: 'customType'} + {validator: validate, msg: '{PATH} failed validation ({VALUE})', type: 'customType'} ]; var schema = new Schema({x: {type: [], validate: validator}}); var M = mongoose.model('custom-validator-' + random(), schema); @@ -720,7 +725,7 @@ describe('schema', function () { user.validate(function (err) { assert.ok(err); assert.ok(user.errors); - assert.ok(user.errors['name']); + assert.ok(user.errors.name); user.name = 'bacon'; user.validate(function (err) { assert.ok(!err); @@ -746,10 +751,10 @@ describe('schema', function () { assert.ok(error); assert.ok(error.errors['foods.0']); assert.equal(error.errors['foods.0'].message, - '`tofu` is not a valid enum value for path `foods`.'); + '`tofu` is not a valid enum value for path `foods`.'); assert.ok(error.errors['foods.1']); assert.equal(error.errors['foods.1'].message, - '`waffles` is not a valid enum value for path `foods`.'); + '`waffles` is not a valid enum value for path `foods`.'); assert.ok(!error.errors['foods.2']); done(); @@ -781,7 +786,7 @@ describe('schema', function () { assert.ok(error); assert.ok(error.errors['votes.0.vote']); assert.equal(error.errors['votes.0.vote'].message, - '`terrible` is not a valid enum value for path `vote`.'); + '`terrible` is not a valid enum value for path `vote`.'); done(); }); @@ -891,7 +896,7 @@ describe('schema', function () { bad.validate(function (error) { assert.ok(error); var errorMessage = 'CastError: Cast to Object failed for value ' + - '"waffles" at path "foods"'; + '"waffles" at path "foods"'; assert.ok(error.toString().indexOf(errorMessage) !== -1, error.toString()); done(); }); @@ -935,8 +940,8 @@ describe('schema', function () { assert.ok(error); assert.equal(Object.keys(error.errors).length, 1); - assert.ok(error.errors['other']); - assert.ok(!error.errors['description']); + assert.ok(error.errors.other); + assert.ok(!error.errors.description); done(); }); @@ -955,7 +960,11 @@ describe('schema', function () { it('sets path correctly when setter throws exception (gh-2832)', function (done) { var breakfast = new Schema({ - description: {type: String, set: function () { throw new Error('oops'); }} + description: { + type: String, set: function () { + throw new Error('oops'); + } + } }); var Breakfast = mongoose.model('gh2832', breakfast, 'gh2832'); @@ -963,8 +972,8 @@ describe('schema', function () { assert.ok(error); var errorMessage = 'ValidationError: CastError: Cast to String failed for value "undefined" at path "description"'; assert.equal(errorMessage, error.toString()); - assert.ok(error.errors['description']); - assert.equal(error.errors['description'].reason.toString(), 'Error: oops'); + assert.ok(error.errors.description); + assert.equal(error.errors.description.reason.toString(), 'Error: oops'); done(); }); }); @@ -991,13 +1000,21 @@ describe('schema', function () { }); it('returns correct kind for user defined custom validators (gh-2885)', function (done) { - var s = mongoose.Schema({n: {type: String, validate: {validator: function () { return false; }}, msg: 'fail'}}); + var s = mongoose.Schema({ + n: { + type: String, validate: { + validator: function () { + return false; + } + }, msg: 'fail' + } + }); var M = mongoose.model('gh2885', s); var m = new M({n: 'test'}); m.validate(function (error) { assert.ok(error); - assert.equal(error.errors['n'].kind, 'user defined'); + assert.equal(error.errors.n.kind, 'user defined'); done(); }); }); @@ -1009,14 +1026,18 @@ describe('schema', function () { var m = new M({n: 'test'}); m.validate(function (error) { assert.ok(error); - assert.equal(error.errors['n'].kind, 'enum'); + assert.equal(error.errors.n.kind, 'enum'); done(); }); }); it('skips conditional required (gh-3539)', function (done) { var s = mongoose.Schema({ - n: {type: Number, required: function () { return false; }, min: 0} + n: { + type: Number, required: function () { + return false; + }, min: 0 + } }); var M = mongoose.model('gh3539', s); diff --git a/test/shard.test.js b/test/shard.test.js index 64be3c20a24..c9a3e404dcf 100644 --- a/test/shard.test.js +++ b/test/shard.test.js @@ -82,7 +82,7 @@ describe('shard', function () { version = info.version.split('.').map(function (n) { return parseInt(n, 10); }); - greaterThan20x = 2 < version[0] || 2 == version[0] && 0 < version[0]; + greaterThan20x = version[0] > 2 || version[0] === 2 && version[0] > 0; done(); }); }); diff --git a/test/types.array.test.js b/test/types.array.test.js index d70af124394..f6b72516d9d 100644 --- a/test/types.array.test.js +++ b/test/types.array.test.js @@ -83,12 +83,6 @@ describe('types array', function () { var pending = 3; - [tobi, loki, jane].forEach(function (pet) { - pet.save(function () { - --pending || cb(); - }); - }); - function cb() { Pet.find({}, function (err) { assert.ifError(err); @@ -108,6 +102,12 @@ describe('types array', function () { }); }); } + + [tobi, loki, jane].forEach(function (pet) { + pet.save(function () { + --pending || cb(); + }); + }); }); }); diff --git a/test/types.documentarray.test.js b/test/types.documentarray.test.js index ada0a50f42d..65a02d50c20 100644 --- a/test/types.documentarray.test.js +++ b/test/types.documentarray.test.js @@ -154,8 +154,8 @@ describe('types.documentarray', function () { sub4 = new Subdocument(); sub4.title = 'rock-n-roll'; - a = new MongooseDocumentArray([sub4]), - threw = false; + a = new MongooseDocumentArray([sub4]); + threw = false; try { a.id('i better not throw'); } catch (err) { diff --git a/test/utils.test.js b/test/utils.test.js index 647b88dd45e..9b66a1d3b17 100644 --- a/test/utils.test.js +++ b/test/utils.test.js @@ -35,21 +35,21 @@ describe('utils', function () { it('should detect a path as required if it has been required', function (done) { var ar = new ActiveRoster(); ar.require('hello'); - assert.equal(ar.paths['hello'], 'require'); + assert.equal(ar.paths.hello, 'require'); done(); }); it('should detect a path as inited if it has been inited', function (done) { var ar = new ActiveRoster(); ar.init('hello'); - assert.equal(ar.paths['hello'], 'init'); + assert.equal(ar.paths.hello, 'init'); done(); }); it('should detect a path as modified', function (done) { var ar = new ActiveRoster(); ar.modify('hello'); - assert.equal(ar.paths['hello'], 'modify'); + assert.equal(ar.paths.hello, 'modify'); done(); }); diff --git a/test/versioning.test.js b/test/versioning.test.js index 7f26b07157f..bc76dfcd673 100644 --- a/test/versioning.test.js +++ b/test/versioning.test.js @@ -91,111 +91,113 @@ describe('versioning', function () { ]; doc.arr = [['2d']]; - doc.save(function (err) { - var a, b; - assert.ifError(err); - // test 2 concurrent ops - V.findById(doc, function (err, _a) { - assert.ifError(err); - a = _a; - if (a && b) { - test1(a, b); - } - }); - V.findById(doc, function (err, _b) { - assert.ifError(err); - b = _b; - if (a && b) { - test1(a, b); + function save(a, b, cb) { + var e; + function lookup() { + var a1, b1; + V.findById(a, function (err, a_) { + if (err && !e) { + e = err; + } + a1 = a_; + if (a1 && b1) { + cb(e, a1, b1); + } + }); + V.findById(b, function (err, b_) { + if (err && !e) { + e = err; + } + b1 = b_; + if (a1 && b1) { + cb(e, a1, b1); + } + }); + } + // make sure that a saves before b + a.save(function (err) { + if (err) { + e = err; } + b.save(function (err) { + if (err) { + e = err; + } + lookup(); + }); }); - }); + } - function test1(a, b) { - a.meta.numbers.push(9); - b.meta.numbers.push(8); - save(a, b, test2); + function test15(err, a) { + assert.equal(a._doc.__v, 13, 'version should not be incremented for non-versioned sub-document fields'); + done(); } - function test2(err, a, b) { + function test14(err, a, b) { assert.ifError(err); - assert.equal(a.meta.numbers.length, 5); - assert.equal(a._doc.__v, 2); - a.meta.numbers.pull(10); - b.meta.numbers.push(20); - save(a, b, test3); + assert.equal(a._doc.__v, 13, 'version should not be incremented for non-versioned fields'); + a.comments[0].dontVersionMeEither.push('value1'); + b.comments[0].dontVersionMeEither.push('value2'); + save(a, b, test15); } - function test3(err, a, b) { + function test13(err, a, b) { assert.ifError(err); - assert.equal(a.meta.numbers.length, 5); - assert.equal(b.meta.numbers.length, 5); - assert.equal(-1, a.meta.numbers.indexOf(10)); - assert.ok(~a.meta.numbers.indexOf(20)); - assert.equal(a._doc.__v, 4); - - a.numbers.pull(3, 20); - - // should fail - b.set('numbers.2', 100); - save(a, b, test4); + a.dontVersionMe.push('value1'); + b.dontVersionMe.push('value2'); + save(a, b, test14); } - function test4(err, a, b) { - assert.ok(/No matching document/.test(err), err); - assert.equal(a._doc.__v, 5); - a.set('arr.0.0', 'updated'); + function test12(err, a, b) { + assert.ok(err instanceof VersionError); + assert.ok(/No matching document/.test(err), 'changes to b should not be applied'); + assert.equal(5, a.comments.length); + + a.comments.addToSet({title: 'aven'}); + a.comments.addToSet({title: 'avengers'}); var d = a.$__delta(); - assert.equal(a._doc.__v, d[0].__v, 'version should be added to where clause'); - assert.ok(!('$inc' in d[1])); - save(a, b, test5); - } - function test5(err, a, b) { - assert.ifError(err); - assert.equal('updated', a.arr[0][0]); - assert.equal(a._doc.__v, 5); - a.set('arr.0', 'not an array'); - // should overwrite a's changes, last write wins - b.arr.pull(10); - b.arr.addToSet('using set'); - save(a, b, test6); + assert.equal(undefined, d[0].__v, 'version should not be included in where clause'); + assert.ok(!d[1].$set); + assert.ok(d[1].$addToSet); + assert.ok(d[1].$addToSet.comments); + + a.comments.$shift(); + d = a.$__delta(); + assert.equal(12, d[0].__v, 'version should be included in where clause'); + assert.ok(d[1].$set, 'two differing atomic ops on same path should create a $set'); + assert.ok(d[1].$inc, 'a $set of an array should trigger versioning'); + assert.ok(!d[1].$addToSet); + save(a, b, test13); } - function test6(err, a, b) { + function test11(err, a, b) { assert.ifError(err); - assert.equal(a.arr.length, 2); - assert.equal('updated', a.arr[0][0]); - assert.equal('using set', a.arr[1]); - assert.equal(a._doc.__v, 6); - b.set('arr.0', 'not an array'); - // should overwrite b's changes, last write wins - // force a $set - a.arr.pull('using set'); - a.arr.push('woot', 'woot2'); - a.arr.$pop(); - save(a, b, test7); - } + assert.equal(a._doc.__v, 11); + assert.equal(6, a.mixed.arr.length); + assert.equal(1, a.mixed.arr[4].x); + assert.equal('woot', a.mixed.arr[5]); + assert.equal(10, a.mixed.arr[3][0]); - function test7(err, a, b) { - assert.ok(/No matching document/.test(err), 'changes to b should not be applied'); - assert.equal(a.arr.length, 2); - assert.equal('updated', a.arr[0][0]); - assert.equal('woot', a.arr[1]); - assert.equal(a._doc.__v, 7); - a.meta.nested.$pop(); - b.meta.nested.$pop(); - save(a, b, test8); + a.comments.addToSet({title: 'monkey'}); + b.markModified('comments'); + + var d = b.$__delta(); + assert.ok(d[1].$inc, 'a $set of an array should trigger versioning'); + + save(a, b, test12); } - function test8(err, a, b) { - assert.ok(/No matching document/.test(err), 'changes to b should not be applied'); - assert.equal(a.meta.nested.length, 3); - assert.equal(a._doc.__v, 8); - a.meta.nested.push({title: 'the'}); - a.meta.nested.push({title: 'killing'}); - b.meta.nested.push({title: 'biutiful'}); - save(a, b, test9); + function test10(err, a, b) { + assert.ifError(err); + assert.equal('two', b.meta.nested[2].title); + assert.equal('zero', b.meta.nested[0].title); + assert.equal('sub one', b.meta.nested[1].comments[0].title); + assert.equal(a._doc.__v, 10); + assert.equal(3, a.mixed.arr.length); + a.mixed.arr.push([10], {x: 1}, 'woot'); + a.markModified('mixed.arr'); + save(a, b, test11); } function test9(err, a, b) { @@ -214,114 +216,112 @@ describe('versioning', function () { }); } - function test10(err, a, b) { - assert.ifError(err); - assert.equal('two', b.meta.nested[2].title); - assert.equal('zero', b.meta.nested[0].title); - assert.equal('sub one', b.meta.nested[1].comments[0].title); - assert.equal(a._doc.__v, 10); - assert.equal(3, a.mixed.arr.length); - a.mixed.arr.push([10], {x: 1}, 'woot'); - a.markModified('mixed.arr'); - save(a, b, test11); + function test8(err, a, b) { + assert.ok(/No matching document/.test(err), 'changes to b should not be applied'); + assert.equal(a.meta.nested.length, 3); + assert.equal(a._doc.__v, 8); + a.meta.nested.push({title: 'the'}); + a.meta.nested.push({title: 'killing'}); + b.meta.nested.push({title: 'biutiful'}); + save(a, b, test9); } - function test11(err, a, b) { - assert.ifError(err); - assert.equal(a._doc.__v, 11); - assert.equal(6, a.mixed.arr.length); - assert.equal(1, a.mixed.arr[4].x); - assert.equal('woot', a.mixed.arr[5]); - assert.equal(10, a.mixed.arr[3][0]); - - a.comments.addToSet({title: 'monkey'}); - b.markModified('comments'); - - var d = b.$__delta(); - assert.ok(d[1].$inc, 'a $set of an array should trigger versioning'); + function test7(err, a, b) { + assert.ok(/No matching document/.test(err), 'changes to b should not be applied'); + assert.equal(a.arr.length, 2); + assert.equal('updated', a.arr[0][0]); + assert.equal('woot', a.arr[1]); + assert.equal(a._doc.__v, 7); + a.meta.nested.$pop(); + b.meta.nested.$pop(); + save(a, b, test8); + } - save(a, b, test12); + function test6(err, a, b) { + assert.ifError(err); + assert.equal(a.arr.length, 2); + assert.equal('updated', a.arr[0][0]); + assert.equal('using set', a.arr[1]); + assert.equal(a._doc.__v, 6); + b.set('arr.0', 'not an array'); + // should overwrite b's changes, last write wins + // force a $set + a.arr.pull('using set'); + a.arr.push('woot', 'woot2'); + a.arr.$pop(); + save(a, b, test7); } - function test12(err, a, b) { - assert.ok(err instanceof VersionError); - assert.ok(/No matching document/.test(err), 'changes to b should not be applied'); - assert.equal(5, a.comments.length); + function test5(err, a, b) { + assert.ifError(err); + assert.equal('updated', a.arr[0][0]); + assert.equal(a._doc.__v, 5); + a.set('arr.0', 'not an array'); + // should overwrite a's changes, last write wins + b.arr.pull(10); + b.arr.addToSet('using set'); + save(a, b, test6); + } - a.comments.addToSet({title: 'aven'}); - a.comments.addToSet({title: 'avengers'}); + function test4(err, a, b) { + assert.ok(/No matching document/.test(err), err); + assert.equal(a._doc.__v, 5); + a.set('arr.0.0', 'updated'); var d = a.$__delta(); - - assert.equal(undefined, d[0].__v, 'version should not be included in where clause'); - assert.ok(!d[1].$set); - assert.ok(d[1].$addToSet); - assert.ok(d[1].$addToSet.comments); - - a.comments.$shift(); - d = a.$__delta(); - assert.equal(12, d[0].__v, 'version should be included in where clause'); - assert.ok(d[1].$set, 'two differing atomic ops on same path should create a $set'); - assert.ok(d[1].$inc, 'a $set of an array should trigger versioning'); - assert.ok(!d[1].$addToSet); - save(a, b, test13); + assert.equal(a._doc.__v, d[0].__v, 'version should be added to where clause'); + assert.ok(!('$inc' in d[1])); + save(a, b, test5); } - function test13(err, a, b) { + function test3(err, a, b) { assert.ifError(err); - a.dontVersionMe.push('value1'); - b.dontVersionMe.push('value2'); - save(a, b, test14); + assert.equal(a.meta.numbers.length, 5); + assert.equal(b.meta.numbers.length, 5); + assert.equal(-1, a.meta.numbers.indexOf(10)); + assert.ok(~a.meta.numbers.indexOf(20)); + assert.equal(a._doc.__v, 4); + + a.numbers.pull(3, 20); + + // should fail + b.set('numbers.2', 100); + save(a, b, test4); } - function test14(err, a, b) { + function test2(err, a, b) { assert.ifError(err); - assert.equal(a._doc.__v, 13, 'version should not be incremented for non-versioned fields'); - a.comments[0].dontVersionMeEither.push('value1'); - b.comments[0].dontVersionMeEither.push('value2'); - save(a, b, test15); + assert.equal(a.meta.numbers.length, 5); + assert.equal(a._doc.__v, 2); + a.meta.numbers.pull(10); + b.meta.numbers.push(20); + save(a, b, test3); } - function test15(err, a) { - assert.equal(a._doc.__v, 13, 'version should not be incremented for non-versioned sub-document fields'); - done(); + function test1(a, b) { + a.meta.numbers.push(9); + b.meta.numbers.push(8); + save(a, b, test2); } - function save(a, b, cb) { - var e; - // make sure that a saves before b - a.save(function (err) { - if (err) { - e = err; + doc.save(function (err) { + var a, b; + assert.ifError(err); + // test 2 concurrent ops + V.findById(doc, function (err, _a) { + assert.ifError(err); + a = _a; + if (a && b) { + test1(a, b); } - b.save(function (err) { - if (err) { - e = err; - } - lookup(); - }); }); - function lookup() { - var a1, b1; - V.findById(a, function (err, a_) { - if (err && !e) { - e = err; - } - a1 = a_; - if (a1 && b1) { - cb(e, a1, b1); - } - }); - V.findById(b, function (err, b_) { - if (err && !e) { - e = err; - } - b1 = b_; - if (a1 && b1) { - cb(e, a1, b1); - } - }); - } - } + V.findById(doc, function (err, _b) { + assert.ifError(err); + b = _b; + if (a && b) { + test1(a, b); + } + }); + }); }); it('versioning without version key', function (done) { @@ -336,8 +336,6 @@ describe('versioning', function () { {title: 'hi', date: new Date} ]; - doc.save(test); - function test(err) { assert.ifError(err); // test getting docs back from db missing version key @@ -349,6 +347,8 @@ describe('versioning', function () { done(); }); } + + doc.save(test); }); it('version works with strict docs', function (done) { diff --git a/website.js b/website.js index 76f4cace21f..1ca646cbbb6 100644 --- a/website.js +++ b/website.js @@ -9,6 +9,32 @@ var klass = require('./docs/helpers/klass'); // add custom jade filters require('./docs/helpers/filters')(jade); +function getVersion() { + var hist = fs.readFileSync('./History.md', 'utf8').replace(/\r/g, '\n').split('\n'); + for (var i = 0; i < hist.length; ++i) { + var line = (hist[i] || '').trim(); + if (!line) { + continue; + } + var match = /^\s*([^\s]+)\s/.exec(line); + if (match && match[1]) { + return match[1]; + } + } + throw new Error('no match found'); +} + +function getUnstable(ver) { + ver = ver.replace('-pre'); + var spl = ver.split('.'); + spl = spl.map(function (i) { + return parseInt(i, 10); + }); + spl[1]++; + spl[2] = 'x'; + return spl.join('.'); +} + // use last release package.version = getVersion(); package.unstable = getUnstable(package.version); @@ -16,26 +42,6 @@ package.unstable = getUnstable(package.version); var filemap = require('./docs/source'); var files = Object.keys(filemap); -files.forEach(function (file) { - var filename = __dirname + '/' + file; - jadeify(filename, filemap[file]); - - if ('--watch' == process.argv[2]) { - fs.watchFile(filename, {interval: 1000}, function (cur, prev) { - if (cur.mtime > prev.mtime) { - jadeify(filename, filemap[file]); - } - }); - } -}); - -var acquit = require('./docs/source/acquit'); -var acquitFiles = Object.keys(acquit); -acquitFiles.forEach(function (file) { - var filename = __dirname + '/docs/acquit.jade'; - jadeify(filename, acquit[file], __dirname + '/docs/' + file); -}); - function jadeify(filename, options, newfile) { options = options || {}; options.package = package; @@ -45,41 +51,37 @@ function jadeify(filename, options, newfile) { options.klass = klass; jade.renderFile(filename, options, function (err, str) { if (err) { - return console.error(err.stack); + console.error(err.stack); + return; } newfile = newfile || filename.replace('.jade', '.html'); fs.writeFile(newfile, str, function (err) { if (err) { - return console.error('could not write', err.stack); + console.error('could not write', err.stack); + } else { + console.log('%s : rendered ', new Date, newfile); } - console.log('%s : rendered ', new Date, newfile); }); }); } -function getVersion() { - var hist = fs.readFileSync('./History.md', 'utf8').replace(/\r/g, '\n').split('\n'); - for (var i = 0; i < hist.length; ++i) { - var line = (hist[i] || '').trim(); - if (!line) { - continue; - } - var match = /^\s*([^\s]+)\s/.exec(line); - if (match && match[1]) { - return match[1]; - } +files.forEach(function (file) { + var filename = __dirname + '/' + file; + jadeify(filename, filemap[file]); + + if ('--watch' === process.argv[2]) { + fs.watchFile(filename, {interval: 1000}, function (cur, prev) { + if (cur.mtime > prev.mtime) { + jadeify(filename, filemap[file]); + } + }); } - throw new Error('no match found'); -} +}); -function getUnstable(ver) { - ver = ver.replace('-pre'); - var spl = ver.split('.'); - spl = spl.map(function (i) { - return parseInt(i, 10); - }); - spl[1]++; - spl[2] = 'x'; - return spl.join('.'); -} +var acquit = require('./docs/source/acquit'); +var acquitFiles = Object.keys(acquit); +acquitFiles.forEach(function (file) { + var filename = __dirname + '/docs/acquit.jade'; + jadeify(filename, acquit[file], __dirname + '/docs/' + file); +});