Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 3 additions & 10 deletions lib/cast.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ module.exports = function cast(schema, obj, options, context) {
val[k] = cast(discriminatorSchema ? discriminatorSchema : schema, val[k], options, context);
}

if (Object.keys(val[k]).length === 0 && beforeCastKeysLength !== 0) {
if (utils.hasOwnKeys(val[k]) === false && beforeCastKeysLength !== 0) {
val.splice(k, 1);
}
}
Expand Down Expand Up @@ -126,10 +126,7 @@ module.exports = function cast(schema, obj, options, context) {
const pathFirstHalf = split.slice(0, j).join('.');
const pathLastHalf = split.slice(j).join('.');
const _schematype = schema.path(pathFirstHalf);
const discriminatorKey = _schematype &&
_schematype.schema &&
_schematype.schema.options &&
_schematype.schema.options.discriminatorKey;
const discriminatorKey = _schematype?.schema?.options?.discriminatorKey;

// gh-6027: if we haven't found the schematype but this path is
// underneath an embedded discriminator and the embedded discriminator
Expand Down Expand Up @@ -430,11 +427,7 @@ function getStrictQuery(queryOptions, schemaUserProvidedOptions, schemaOptions,
if ('strictQuery' in schemaUserProvidedOptions) {
return schemaUserProvidedOptions.strictQuery;
}
const mongooseOptions = context &&
context.mongooseCollection &&
context.mongooseCollection.conn &&
context.mongooseCollection.conn.base &&
context.mongooseCollection.conn.base.options;
const mongooseOptions = context?.mongooseCollection?.conn?.base?.options;
if (mongooseOptions) {
if ('strictQuery' in mongooseOptions) {
return mongooseOptions.strictQuery;
Expand Down
18 changes: 12 additions & 6 deletions lib/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -630,7 +630,7 @@ Connection.prototype.createCollections = async function createCollections(option
}
}

if (!continueOnError && Object.keys(errorsMap).length) {
if (!continueOnError && utils.hasOwnKeys(errorsMap)) {
const message = Object.entries(errorsMap).map(([modelName, err]) => `${modelName}: ${err.message}`).join(', ');
const createCollectionsError = new CreateCollectionsError(message, errorsMap);
throw createCollectionsError;
Expand Down Expand Up @@ -1250,8 +1250,11 @@ Connection.prototype._close = async function _close(force, destroy) {
const conn = this;
switch (this.readyState) {
case STATES.disconnected:
if (destroy && this.base.connections.indexOf(conn) !== -1) {
this.base.connections.splice(this.base.connections.indexOf(conn), 1);
if (destroy) {
const index = this.base.connections.indexOf(conn);
if (index !== -1) {
this.base.connections.splice(index, 1);
}
}
if (!closeCalled) {
await this.doClose(force);
Expand All @@ -1262,8 +1265,11 @@ Connection.prototype._close = async function _close(force, destroy) {
case STATES.connected:
this.readyState = STATES.disconnecting;
await this.doClose(force);
if (destroy && _this.base.connections.indexOf(conn) !== -1) {
this.base.connections.splice(this.base.connections.indexOf(conn), 1);
if (destroy) {
const index = _this.base.connections.indexOf(conn);
if (index !== -1) {
this.base.connections.splice(index, 1);
}
}
this.onClose(force);

Expand Down Expand Up @@ -1772,7 +1778,7 @@ Connection.prototype.syncIndexes = async function syncIndexes(options = {}) {
}
}

if (!continueOnError && Object.keys(errorsMap).length) {
if (!continueOnError && utils.hasOwnKeys(errorsMap)) {
const message = Object.entries(errorsMap).map(([modelName, err]) => `${modelName}: ${err.message}`).join(', ');
const syncIndexesError = new SyncIndexesError(message, errorsMap);
throw syncIndexesError;
Expand Down
4 changes: 2 additions & 2 deletions lib/cursor/changeStream.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ class ChangeStream extends EventEmitter {

driverChangeStreamEvents.forEach(ev => {
this.driverChangeStream.on(ev, data => {
if (data != null && data.fullDocument != null && this.options && this.options.hydrate) {
if (data?.fullDocument != null && this.options?.hydrate) {
data.fullDocument = this.options.model.hydrate(data.fullDocument);
}
this.emit(ev, data);
Expand All @@ -102,7 +102,7 @@ class ChangeStream extends EventEmitter {

driverChangeStreamEvents.forEach(ev => {
this.driverChangeStream.on(ev, data => {
if (data != null && data.fullDocument != null && this.options && this.options.hydrate) {
if (data?.fullDocument != null && this.options?.hydrate) {
data.fullDocument = this.options.model.hydrate(data.fullDocument);
}
this.emit(ev, data);
Expand Down
28 changes: 16 additions & 12 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ function Document(obj, fields, options) {

// determine if this doc is a result of a query with
// excluded fields
if (utils.isPOJO(fields) && Object.keys(fields).length > 0) {
if (utils.isPOJO(fields) && utils.hasOwnKeys(fields)) {
exclude = isExclusive(fields);
this.$__.selected = fields;
this.$__.exclude = exclude;
Expand Down Expand Up @@ -1015,17 +1015,21 @@ Document.prototype.$timestamps = function $timestamps(value) {
*/

Document.prototype.overwrite = function overwrite(obj) {
const keys = Array.from(new Set(Object.keys(this._doc).concat(Object.keys(obj))));
const keys = new Set(Object.keys(this._doc));
for (const key of Object.keys(obj)) {
keys.add(key);
}

const schemaOptions = this.$__schema.options;
for (const key of keys) {
if (key === '_id') {
continue;
}
// Explicitly skip version key
if (this.$__schema.options.versionKey && key === this.$__schema.options.versionKey) {
if (schemaOptions.versionKey && key === schemaOptions.versionKey) {
continue;
}
if (this.$__schema.options.discriminatorKey && key === this.$__schema.options.discriminatorKey) {
if (schemaOptions.discriminatorKey && key === schemaOptions.discriminatorKey) {
continue;
}
this.$set(key, obj[key]);
Expand Down Expand Up @@ -1697,7 +1701,7 @@ Document.prototype.$__set = function(pathToMark, path, options, constructing, pa
if (shouldModify) {
if (this.$__.primitiveAtomics && this.$__.primitiveAtomics[path]) {
delete this.$__.primitiveAtomics[path];
if (Object.keys(this.$__.primitiveAtomics).length === 0) {
if (utils.hasOwnKeys(this.$__.primitiveAtomics) === false) {
delete this.$__.primitiveAtomics;
}
}
Expand Down Expand Up @@ -3001,7 +3005,7 @@ Document.prototype.$__validate = async function $__validate(pathsToValidate, opt
delete validationError.errors[errPath];
}
}
if (Object.keys(validationError.errors).length === 0) {
if (utils.hasOwnKeys(validationError.errors) === false) {
validationError = void 0;
}
}
Expand Down Expand Up @@ -3402,7 +3406,7 @@ Document.prototype.$markValid = function(path) {
}

delete this.$__.validationError.errors[path];
if (Object.keys(this.$__.validationError.errors).length === 0) {
if (utils.hasOwnKeys(this.$__.validationError.errors) === false) {
this.$__.validationError = null;
}
};
Expand All @@ -3422,7 +3426,7 @@ function _markValidSubpaths(doc, path) {
delete doc.$__.validationError.errors[key];
}
}
if (Object.keys(doc.$__.validationError.errors).length === 0) {
if (utils.hasOwnKeys(doc.$__.validationError.errors) === false) {
doc.$__.validationError = null;
}
}
Expand Down Expand Up @@ -3497,7 +3501,7 @@ function _checkImmutableSubpaths(subdoc, schematype, priorVal) {
*/

Document.prototype.$isValid = function(path) {
if (this.$__.validationError == null || Object.keys(this.$__.validationError.errors).length === 0) {
if (this.$__.validationError == null || utils.hasOwnKeys(this.$__.validationError.errors) === false) {
return true;
}
if (path == null) {
Expand Down Expand Up @@ -4375,7 +4379,7 @@ function omitDeselectedFields(self, json) {
selected = {};
queryhelpers.applyPaths(selected, schema);
}
if (selected == null || Object.keys(selected).length === 0) {
if (selected == null || utils.hasOwnKeys(selected) === false) {
return json;
}

Expand Down Expand Up @@ -5057,7 +5061,7 @@ Document.prototype.$__delta = function $__delta() {
this.$__version(where, delta);
}

if (Object.keys(delta).length === 0) {
if (utils.hasOwnKeys(delta) === false) {
return [where, null];
}

Expand Down Expand Up @@ -5109,7 +5113,7 @@ function checkDivergentArray(doc, path, array) {

if (check) {
const atomics = array[arrayAtomicsSymbol];
if (Object.keys(atomics).length === 0 || atomics.$set || atomics.$pop) {
if (utils.hasOwnKeys(atomics) === false || atomics.$set || atomics.$pop) {
return path;
}
}
Expand Down
18 changes: 3 additions & 15 deletions lib/drivers/node-mongodb-native/collection.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,15 +97,8 @@ function iter(i) {
const collection = this._getCollection();
const args = Array.from(arguments);
const _this = this;
const globalDebug = _this &&
_this.conn &&
_this.conn.base &&
_this.conn.base.options &&
_this.conn.base.options.debug;
const connectionDebug = _this &&
_this.conn &&
_this.conn.options &&
_this.conn.options.debug;
const globalDebug = _this?.conn?.base?.options?.debug;
const connectionDebug = _this?.conn?.options?.debug;
const debug = connectionDebug == null ? globalDebug : connectionDebug;
const lastArg = arguments[arguments.length - 1];
const opId = new ObjectId();
Expand Down Expand Up @@ -428,12 +421,7 @@ function format(obj, sub, color, shell) {
formatDate(x, key, shell);
} else if (_constructorName === 'ClientSession') {
x[key] = inspectable('ClientSession("' +
(
x[key] &&
x[key].id &&
x[key].id.id &&
x[key].id.id.buffer || ''
).toString('hex') + '")');
(x[key]?.id?.id?.buffer || '').toString('hex') + '")');
} else if (Array.isArray(x[key])) {
x[key] = x[key].map(map);
} else if (error != null) {
Expand Down
25 changes: 6 additions & 19 deletions lib/drivers/node-mongodb-native/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -316,15 +316,15 @@ NativeConnection.prototype.createClient = async function createClient(uri, optio

const { schemaMap, encryptedFieldsMap } = this._buildEncryptionSchemas();

if ((Object.keys(schemaMap).length > 0 || Object.keys(encryptedFieldsMap).length) && !options.autoEncryption) {
if ((utils.hasOwnKeys(schemaMap) || utils.hasOwnKeys(encryptedFieldsMap)) && !options.autoEncryption) {
throw new Error('Must provide `autoEncryption` when connecting with encrypted schemas.');
}

if (Object.keys(schemaMap).length > 0) {
if (utils.hasOwnKeys(schemaMap)) {
options.autoEncryption.schemaMap = schemaMap;
}

if (Object.keys(encryptedFieldsMap).length > 0) {
if (utils.hasOwnKeys(encryptedFieldsMap)) {
options.autoEncryption.encryptedFieldsMap = encryptedFieldsMap;
}

Expand Down Expand Up @@ -435,18 +435,8 @@ function _setClient(conn, client, options, dbName) {
const db = dbName != null ? client.db(dbName) : client.db();
conn.db = db;
conn.client = client;
conn.host = client &&
client.s &&
client.s.options &&
client.s.options.hosts &&
client.s.options.hosts[0] &&
client.s.options.hosts[0].host || void 0;
conn.port = client &&
client.s &&
client.s.options &&
client.s.options.hosts &&
client.s.options.hosts[0] &&
client.s.options.hosts[0].port || void 0;
conn.host = client?.s?.options?.hosts?.[0]?.host;
conn.port = client?.s?.options?.hosts?.[0]?.port;
conn.name = dbName != null ? dbName : db.databaseName;
conn._closeCalled = client._closeCalled;

Expand All @@ -463,10 +453,7 @@ function _setClient(conn, client, options, dbName) {
}
};

const type = client &&
client.topology &&
client.topology.description &&
client.topology.description.type || '';
const type = client?.topology?.description?.type || '';

if (type === 'Single') {
client.on('serverDescriptionChanged', ev => {
Expand Down
3 changes: 2 additions & 1 deletion lib/helpers/document/applyTimestamps.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const handleTimestampOption = require('../schema/handleTimestampOption');
const mpath = require('mpath');
const utils = require('../../utils');

module.exports = applyTimestamps;

Expand Down Expand Up @@ -71,7 +72,7 @@ function applyTimestampsToDoc(schema, obj, options) {
return;
}

if (schema.discriminators && Object.keys(schema.discriminators).length > 0) {
if (schema.discriminators && utils.hasOwnKeys(schema.discriminators)) {
for (const discriminatorKey of Object.keys(schema.discriminators)) {
const discriminator = schema.discriminators[discriminatorKey];
const key = discriminator.discriminatorMapping.key;
Expand Down
3 changes: 2 additions & 1 deletion lib/helpers/document/applyVirtuals.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

const mpath = require('mpath');
const utils = require('../../utils');

module.exports = applyVirtuals;

Expand Down Expand Up @@ -101,7 +102,7 @@ function applyVirtualsToDoc(schema, obj, virtuals) {
return;
}

if (schema.discriminators && Object.keys(schema.discriminators).length > 0) {
if (schema.discriminators && utils.hasOwnKeys(schema.discriminators)) {
for (const discriminatorKey of Object.keys(schema.discriminators)) {
const discriminator = schema.discriminators[discriminatorKey];
const key = discriminator.discriminatorMapping.key;
Expand Down
6 changes: 3 additions & 3 deletions lib/helpers/document/compile.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ function compile(tree, proto, prefix, options) {
const limb = tree[key];

const hasSubprops = isPOJO(limb) &&
Object.keys(limb).length > 0 &&
utils.hasOwnKeys(limb) &&
(!limb[typeKey] || (typeKey === 'type' && isPOJO(limb.type) && limb.type.type));
const subprops = hasSubprops ? limb : null;

Expand Down Expand Up @@ -132,7 +132,7 @@ function defineKey({ prop, subprops, prototype, prefix, options }) {
writable: false,
value: function() {
return _this.get(path, null, {
virtuals: this && this.schema && this.schema.options && this.schema.options.toObject && this.schema.options.toObject.virtuals || null
virtuals: this?.schema?.options?.toObject?.virtuals || null
});
}
});
Expand All @@ -143,7 +143,7 @@ function defineKey({ prop, subprops, prototype, prefix, options }) {
writable: false,
value: function() {
return _this.get(path, null, {
virtuals: this && this.schema && this.schema.options && this.schema.options.toJSON && this.schema.options.toJSON.virtuals || null
virtuals: this?.schema?.options?.toJSON?.virtuals || null
});
}
});
Expand Down
11 changes: 7 additions & 4 deletions lib/helpers/populate/getModelsMapForPopulate.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ module.exports = function getModelsMapForPopulate(model, docs, options) {
let schema;
let refPath;
let modelNames;
let modelNamesSet;
const available = {};

const modelSchema = model.schema;
Expand Down Expand Up @@ -123,8 +124,10 @@ module.exports = function getModelsMapForPopulate(model, docs, options) {
continue;
}
modelNames = modelNames || [];
modelNamesSet = modelNamesSet || new Set();
for (const modelName of _modelNames) {
if (modelNames.indexOf(modelName) === -1) {
if (modelNamesSet.has(modelName) === false) {
modelNamesSet.add(modelName);
modelNames.push(modelName);
}
}
Expand Down Expand Up @@ -225,8 +228,8 @@ module.exports = function getModelsMapForPopulate(model, docs, options) {
schema = schema.$__schemaType;
}

const ref = schema && schema.options && schema.options.ref;
refPath = schema && schema.options && schema.options.refPath;
const ref = schema?.options?.ref;
refPath = schema?.options?.refPath;
if (schema != null &&
schema[schemaMixedSymbol] &&
!ref &&
Expand Down Expand Up @@ -721,7 +724,7 @@ function _findRefPathForDiscriminators(doc, modelSchema, data, options, normaliz
if (schematype != null &&
schematype.$isMongooseDocumentArray &&
schematype.Constructor.discriminators != null &&
Object.keys(schematype.Constructor.discriminators).length !== 0) {
utils.hasOwnKeys(schematype.Constructor.discriminators)) {
const subdocs = utils.getValue(cur, doc);
const remnant = options.path.substring(cur.length + 1);
const discriminatorKey = schematype.Constructor.schema.options.discriminatorKey;
Expand Down
Loading