mongoose 6.3.4 → 6.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const isBsonType = require('../helpers/isBsonType');
3
4
  const ObjectId = require('../driver').get().ObjectId;
4
5
 
5
6
  module.exports = function castObjectId(value) {
@@ -7,12 +8,12 @@ module.exports = function castObjectId(value) {
7
8
  return value;
8
9
  }
9
10
 
10
- if (value instanceof ObjectId) {
11
+ if (isBsonType(value, 'ObjectID')) {
11
12
  return value;
12
13
  }
13
14
 
14
15
  if (value._id) {
15
- if (value._id instanceof ObjectId) {
16
+ if (isBsonType(value._id, 'ObjectID')) {
16
17
  return value._id;
17
18
  }
18
19
  if (value._id.toString instanceof Function) {
package/lib/connection.js CHANGED
@@ -548,7 +548,7 @@ Connection.prototype.dropDatabase = _wrapConnHelper(function dropDatabase(cb) {
548
548
  // If `dropDatabase()` is called, this model's collection will not be
549
549
  // init-ed. It is sufficiently common to call `dropDatabase()` after
550
550
  // `mongoose.connect()` but before creating models that we want to
551
- // support this. See gh-6967
551
+ // support this. See gh-6796
552
552
  for (const name of Object.keys(this.models)) {
553
553
  delete this.models[name].$init;
554
554
  }
package/lib/document.js CHANGED
@@ -1378,7 +1378,7 @@ Document.prototype.$set = function $set(path, val, type, options) {
1378
1378
  })();
1379
1379
 
1380
1380
  let didPopulate = false;
1381
- if (refMatches && val instanceof Document) {
1381
+ if (refMatches && val instanceof Document && (!val.$__.wasPopulated || utils.deepEqual(val.$__.wasPopulated.value, val._id))) {
1382
1382
  const unpopulatedValue = (schema && schema.$isSingleNested) ? schema.cast(val, this) : val._id;
1383
1383
  this.$populated(path, unpopulatedValue, { [populateModelSymbol]: val.constructor });
1384
1384
  val.$__.wasPopulated = { value: unpopulatedValue };
@@ -3464,9 +3464,9 @@ Document.prototype.$toObject = function(options, json) {
3464
3464
 
3465
3465
  const path = json ? 'toJSON' : 'toObject';
3466
3466
  const baseOptions = this.constructor &&
3467
- this.constructor.base &&
3468
- this.constructor.base.options &&
3469
- get(this.constructor.base.options, path) || {};
3467
+ this.constructor.base &&
3468
+ this.constructor.base.options &&
3469
+ get(this.constructor.base.options, path) || {};
3470
3470
  const schemaOptions = this.$__schema && this.$__schema.options || {};
3471
3471
  // merge base default options with Schema's set default options if available.
3472
3472
  // `clone` is necessary here because `utils.options` directly modifies the second input.
@@ -3503,7 +3503,8 @@ Document.prototype.$toObject = function(options, json) {
3503
3503
  _isNested: true,
3504
3504
  json: json,
3505
3505
  minimize: _minimize,
3506
- flattenMaps: flattenMaps
3506
+ flattenMaps: flattenMaps,
3507
+ _seen: (options && options._seen) || new Map()
3507
3508
  });
3508
3509
 
3509
3510
  if (utils.hasUserDefinedProperty(options, 'getters')) {
@@ -5,11 +5,11 @@
5
5
  * Mongoose-specific errors.
6
6
  *
7
7
  * #### Example:
8
- * const Model = mongoose.model('Test', new Schema({ answer: Number }));
8
+ * const Model = mongoose.model('Test', new mongoose.Schema({ answer: Number }));
9
9
  * const doc = new Model({ answer: 'not a number' });
10
10
  * const err = doc.validateSync();
11
11
  *
12
- * err instanceof mongoose.Error; // true
12
+ * err instanceof mongoose.Error.ValidationError; // true
13
13
  *
14
14
  * @constructor Error
15
15
  * @param {String} msg Error message
@@ -77,7 +77,7 @@ function clone(obj, options, isArrayChild) {
77
77
  }
78
78
  }
79
79
 
80
- if (obj instanceof ObjectId) {
80
+ if (isBsonType(obj, 'ObjectID')) {
81
81
  return new ObjectId(obj.id);
82
82
  }
83
83
 
@@ -119,9 +119,15 @@ module.exports = clone;
119
119
  function cloneObject(obj, options, isArrayChild) {
120
120
  const minimize = options && options.minimize;
121
121
  const omitUndefined = options && options.omitUndefined;
122
+ const seen = options && options._seen;
122
123
  const ret = {};
123
124
  let hasKeys;
124
125
 
126
+ if (seen && seen.has(obj)) {
127
+ return seen.get(obj);
128
+ } else if (seen) {
129
+ seen.set(obj, ret);
130
+ }
125
131
  if (trustedSymbol in obj) {
126
132
  ret[trustedSymbol] = obj[trustedSymbol];
127
133
  }
@@ -5,8 +5,7 @@
5
5
  */
6
6
 
7
7
  const Binary = require('../driver').get().Binary;
8
- const Decimal128 = require('../types/decimal128');
9
- const ObjectId = require('../types/objectid');
8
+ const isBsonType = require('./isBsonType');
10
9
  const isMongooseObject = require('./isMongooseObject');
11
10
 
12
11
  exports.flatten = flatten;
@@ -99,9 +98,9 @@ function shouldFlatten(val) {
99
98
  return val &&
100
99
  typeof val === 'object' &&
101
100
  !(val instanceof Date) &&
102
- !(val instanceof ObjectId) &&
101
+ !isBsonType(val, 'ObjectID') &&
103
102
  (!Array.isArray(val) || val.length !== 0) &&
104
103
  !(val instanceof Buffer) &&
105
- !(val instanceof Decimal128) &&
104
+ !isBsonType(val, 'Decimal128') &&
106
105
  !(val instanceof Binary);
107
106
  }
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const ObjectId = require('../../types/objectid');
3
+ const isBsonType = require('../isBsonType');
4
4
 
5
5
  module.exports = function areDiscriminatorValuesEqual(a, b) {
6
6
  if (typeof a === 'string' && typeof b === 'string') {
@@ -9,7 +9,7 @@ module.exports = function areDiscriminatorValuesEqual(a, b) {
9
9
  if (typeof a === 'number' && typeof b === 'number') {
10
10
  return a === b;
11
11
  }
12
- if (a instanceof ObjectId && b instanceof ObjectId) {
12
+ if (isBsonType(a, 'ObjectID') && isBsonType(b, 'ObjectID')) {
13
13
  return a.toString() === b.toString();
14
14
  }
15
15
  return false;
@@ -1,13 +1,15 @@
1
1
  'use strict';
2
2
 
3
- const get = require('./get');
4
-
5
3
  /*!
6
4
  * Get the bson type, if it exists
7
5
  */
8
6
 
9
7
  function isBsonType(obj, typename) {
10
- return get(obj, '_bsontype', void 0) === typename;
8
+ return (
9
+ typeof obj === 'object' &&
10
+ obj !== null &&
11
+ obj._bsontype === typename
12
+ );
11
13
  }
12
14
 
13
15
  module.exports = isBsonType;
@@ -1,14 +1,25 @@
1
1
  'use strict';
2
2
 
3
+ const specialProperties = require('../specialProperties');
4
+
5
+
3
6
  module.exports = function setDottedPath(obj, path, val) {
4
7
  if (path.indexOf('.') === -1) {
8
+ if (specialProperties.has(path)) {
9
+ return;
10
+ }
11
+
5
12
  obj[path] = val;
6
13
  return;
7
14
  }
8
15
  const parts = path.split('.');
16
+
9
17
  const last = parts.pop();
10
18
  let cur = obj;
11
19
  for (const part of parts) {
20
+ if (specialProperties.has(part)) {
21
+ continue;
22
+ }
12
23
  if (cur[part] == null) {
13
24
  cur[part] = {};
14
25
  }
@@ -16,5 +27,7 @@ module.exports = function setDottedPath(obj, path, val) {
16
27
  cur = cur[part];
17
28
  }
18
29
 
19
- cur[last] = val;
30
+ if (!specialProperties.has(last)) {
31
+ cur[last] = val;
32
+ }
20
33
  };
@@ -8,6 +8,19 @@ module.exports = function isAtlas(topologyDescription) {
8
8
  }
9
9
 
10
10
  const hostnames = Array.from(topologyDescription.servers.keys());
11
- return hostnames.length > 0 &&
12
- hostnames.every(host => host.endsWith('.mongodb.net:27017'));
11
+
12
+ if (hostnames.length === 0) {
13
+ return false;
14
+ }
15
+
16
+ for (let i = 0, il = hostnames.length; i < il; ++i) {
17
+ const url = new URL(hostnames[i]);
18
+ if (
19
+ url.hostname.endsWith('.mongodb.net') === false ||
20
+ url.port !== '27017'
21
+ ) {
22
+ return false;
23
+ }
24
+ }
25
+ return true;
13
26
  };
package/lib/index.js CHANGED
@@ -34,6 +34,7 @@ const PromiseProvider = require('./promise_provider');
34
34
  const shardingPlugin = require('./plugins/sharding');
35
35
  const trusted = require('./helpers/query/trusted').trusted;
36
36
  const sanitizeFilter = require('./helpers/query/sanitizeFilter');
37
+ const isBsonType = require('./helpers/isBsonType');
37
38
 
38
39
  const defaultMongooseSymbol = Symbol.for('mongoose:default');
39
40
 
@@ -995,8 +996,7 @@ Mongoose.prototype.isValidObjectId = function(v) {
995
996
  */
996
997
 
997
998
  Mongoose.prototype.isObjectIdOrHexString = function(v) {
998
- const _mongoose = this instanceof Mongoose ? this : mongoose;
999
- return v instanceof _mongoose.Types.ObjectId || (typeof v === 'string' && objectIdHexRegexp.test(v));
999
+ return isBsonType(v, 'ObjectID') || (typeof v === 'string' && objectIdHexRegexp.test(v));
1000
1000
  };
1001
1001
 
1002
1002
  /**
@@ -6,9 +6,9 @@
6
6
 
7
7
  const SchemaType = require('../schematype');
8
8
  const CastError = SchemaType.CastError;
9
- const Decimal128Type = require('../types/decimal128');
10
9
  const castDecimal128 = require('../cast/decimal128');
11
10
  const utils = require('../utils');
11
+ const isBsonType = require('../helpers/isBsonType');
12
12
 
13
13
  /**
14
14
  * Decimal128 SchemaType constructor.
@@ -105,7 +105,7 @@ Decimal128.cast = function cast(caster) {
105
105
  */
106
106
 
107
107
  Decimal128._defaultCaster = v => {
108
- if (v != null && !(v instanceof Decimal128Type)) {
108
+ if (v != null && !isBsonType(v, 'Decimal128')) {
109
109
  throw new Error();
110
110
  }
111
111
  return v;
@@ -115,7 +115,7 @@ Decimal128._defaultCaster = v => {
115
115
  * ignore
116
116
  */
117
117
 
118
- Decimal128._checkRequired = v => v instanceof Decimal128Type;
118
+ Decimal128._checkRequired = v => isBsonType(v, 'Decimal128');
119
119
 
120
120
  /**
121
121
  * Override the function the required validator uses to check whether a string
@@ -164,7 +164,7 @@ Decimal128.prototype.checkRequired = function checkRequired(value, doc) {
164
164
 
165
165
  Decimal128.prototype.cast = function(value, doc, init) {
166
166
  if (SchemaType._isRef(this, value, doc, init)) {
167
- if (value instanceof Decimal128Type) {
167
+ if (isBsonType(value, 'Decimal128')) {
168
168
  return value;
169
169
  }
170
170
 
@@ -4,12 +4,12 @@
4
4
  * Module dependencies.
5
5
  */
6
6
 
7
- const { BSONRegExp } = require('bson');
8
7
  const SchemaType = require('../schematype');
9
8
  const MongooseError = require('../error/index');
10
9
  const SchemaStringOptions = require('../options/SchemaStringOptions');
11
10
  const castString = require('../cast/string');
12
11
  const utils = require('../utils');
12
+ const isBsonType = require('../helpers/isBsonType');
13
13
 
14
14
  const CastError = SchemaType.CastError;
15
15
 
@@ -677,7 +677,7 @@ SchemaString.prototype.castForQuery = function($conditional, val) {
677
677
  return handler.call(this, val);
678
678
  }
679
679
  val = $conditional;
680
- if (Object.prototype.toString.call(val) === '[object RegExp]' || val instanceof BSONRegExp) {
680
+ if (Object.prototype.toString.call(val) === '[object RegExp]' || isBsonType(val, 'BSONRegExp')) {
681
681
  return val;
682
682
  }
683
683
 
@@ -2,11 +2,11 @@
2
2
 
3
3
  const ArrayMethods = require('../../array/methods');
4
4
  const Document = require('../../../document');
5
- const ObjectId = require('../../objectid');
6
5
  const castObjectId = require('../../../cast/objectid');
7
6
  const getDiscriminatorByValue = require('../../../helpers/discriminator/getDiscriminatorByValue');
8
7
  const internalToObjectOptions = require('../../../options').internalToObjectOptions;
9
8
  const utils = require('../../../utils');
9
+ const isBsonType = require('../../../helpers/isBsonType');
10
10
 
11
11
  const arrayParentSymbol = require('../../../helpers/symbols').arrayParentSymbol;
12
12
  const arrayPathSymbol = require('../../../helpers/symbols').arrayPathSymbol;
@@ -66,7 +66,7 @@ const methods = {
66
66
  // only objects are permitted so we can safely assume that
67
67
  // non-objects are to be interpreted as _id
68
68
  if (Buffer.isBuffer(value) ||
69
- value instanceof ObjectId || !utils.isObject(value)) {
69
+ isBsonType(value, 'ObjectID') || !utils.isObject(value)) {
70
70
  value = { _id: value };
71
71
  }
72
72
 
@@ -134,7 +134,7 @@ const methods = {
134
134
  if (sid == _id._id) {
135
135
  return val;
136
136
  }
137
- } else if (!(id instanceof ObjectId) && !(_id instanceof ObjectId)) {
137
+ } else if (!isBsonType(id, 'ObjectID') && !isBsonType(_id, 'ObjectID')) {
138
138
  if (id == _id || utils.deepEqual(id, _id)) {
139
139
  return val;
140
140
  }
@@ -3,10 +3,10 @@
3
3
  const Document = require('../../../document');
4
4
  const ArraySubdocument = require('../../ArraySubdocument');
5
5
  const MongooseError = require('../../../error/mongooseError');
6
- const ObjectId = require('../../objectid');
7
6
  const cleanModifiedSubpaths = require('../../../helpers/document/cleanModifiedSubpaths');
8
7
  const internalToObjectOptions = require('../../../options').internalToObjectOptions;
9
8
  const utils = require('../../../utils');
9
+ const isBsonType = require('../../../helpers/isBsonType');
10
10
 
11
11
  const arrayAtomicsSymbol = require('../../../helpers/symbols').arrayAtomicsSymbol;
12
12
  const arrayParentSymbol = require('../../../helpers/symbols').arrayParentSymbol;
@@ -227,7 +227,7 @@ const methods = {
227
227
  // only objects are permitted so we can safely assume that
228
228
  // non-objects are to be interpreted as _id
229
229
  if (Buffer.isBuffer(value) ||
230
- value instanceof ObjectId || !utils.isObject(value)) {
230
+ isBsonType(value, 'ObjectID') || !utils.isObject(value)) {
231
231
  value = { _id: value };
232
232
  }
233
233
 
@@ -469,7 +469,7 @@ const methods = {
469
469
  */
470
470
 
471
471
  indexOf(obj, fromIndex) {
472
- if (obj instanceof ObjectId) {
472
+ if (isBsonType(obj, 'ObjectID')) {
473
473
  obj = obj.toString();
474
474
  }
475
475
 
package/lib/types/map.js CHANGED
@@ -1,13 +1,13 @@
1
1
  'use strict';
2
2
 
3
3
  const Mixed = require('../schema/mixed');
4
- const ObjectId = require('./objectid');
5
4
  const clone = require('../helpers/clone');
6
5
  const deepEqual = require('../utils').deepEqual;
7
6
  const getConstructorName = require('../helpers/getConstructorName');
8
7
  const handleSpreadDoc = require('../helpers/document/handleSpreadDoc');
9
8
  const util = require('util');
10
9
  const specialProperties = require('../helpers/specialProperties');
10
+ const isBsonType = require('../helpers/isBsonType');
11
11
 
12
12
  const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
13
13
 
@@ -43,7 +43,7 @@ class MongooseMap extends Map {
43
43
  }
44
44
 
45
45
  get(key, options) {
46
- if (key instanceof ObjectId) {
46
+ if (isBsonType(key, 'ObjectID')) {
47
47
  key = key.toString();
48
48
  }
49
49
 
@@ -55,7 +55,7 @@ class MongooseMap extends Map {
55
55
  }
56
56
 
57
57
  set(key, value) {
58
- if (key instanceof ObjectId) {
58
+ if (isBsonType(key, 'ObjectID')) {
59
59
  key = key.toString();
60
60
  }
61
61
 
@@ -117,7 +117,7 @@ class MongooseMap extends Map {
117
117
  }
118
118
 
119
119
  delete(key) {
120
- if (key instanceof ObjectId) {
120
+ if (isBsonType(key, 'ObjectID')) {
121
121
  key = key.toString();
122
122
  }
123
123
 
package/lib/utils.js CHANGED
@@ -6,7 +6,6 @@
6
6
 
7
7
  const ms = require('ms');
8
8
  const mpath = require('mpath');
9
- const Decimal = require('./types/decimal128');
10
9
  const ObjectId = require('./types/objectid');
11
10
  const PopulateOptions = require('./options/PopulateOptions');
12
11
  const clone = require('./helpers/clone');
@@ -307,7 +306,7 @@ exports.merge = function merge(to, from, options, path) {
307
306
  to[key] = from[key].clone();
308
307
  }
309
308
  continue;
310
- } else if (from[key] instanceof ObjectId) {
309
+ } else if (isBsonType(from[key], 'ObjectID')) {
311
310
  to[key] = new ObjectId(from[key]);
312
311
  continue;
313
312
  }
@@ -481,7 +480,7 @@ exports.tick = function tick(callback) {
481
480
  */
482
481
 
483
482
  exports.isMongooseType = function(v) {
484
- return v instanceof ObjectId || v instanceof Decimal || v instanceof Buffer;
483
+ return isBsonType(v, 'ObjectID') || isBsonType(v, 'Decimal128') || v instanceof Buffer;
485
484
  };
486
485
 
487
486
  exports.isMongooseObject = isMongooseObject;
@@ -795,7 +794,7 @@ exports.array.unique = function(arr) {
795
794
  }
796
795
  ret.push(item);
797
796
  primitives.add(item);
798
- } else if (item instanceof ObjectId) {
797
+ } else if (isBsonType(item, 'ObjectID')) {
799
798
  if (ids.has(item.toString())) {
800
799
  continue;
801
800
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mongoose",
3
3
  "description": "Mongoose MongoDB ODM",
4
- "version": "6.3.4",
4
+ "version": "6.3.5",
5
5
  "author": "Guillermo Rauch <guillermo@learnboost.com>",
6
6
  "keywords": [
7
7
  "mongodb",
@@ -61,6 +61,7 @@
61
61
  "serve-handler": "6.1.3",
62
62
  "sinon": "13.0.2",
63
63
  "stream-browserify": "3.0.0",
64
+ "ts-benchmark": "^1.0.2",
64
65
  "tsd": "0.20.0",
65
66
  "typescript": "4.6.4",
66
67
  "uuid": "8.3.2",
@@ -97,7 +98,9 @@
97
98
  "test-rs": "START_REPLICA_SET=1 mocha --timeout 30000 --exit ./test/*.test.js",
98
99
  "test-tsd": "node ./test/types/check-types-filename && tsd",
99
100
  "tdd": "mocha ./test/*.test.js ./test/typescript/main.test.js --inspect --watch --recursive --watch-files ./**/*.js",
100
- "test-coverage": "nyc --reporter=html --reporter=text npm test"
101
+ "test-coverage": "nyc --reporter=html --reporter=text npm test",
102
+ "ts-benchmark": "ts-benchmark -p ./benchmarks/typescript/simple -f 17 18 29 32",
103
+ "ts-benchmark-watch": "ts-benchmark -p ./benchmarks/typescript/simple -w ./types -i -s -f 17 18 29 32 -b master"
101
104
  },
102
105
  "main": "./index.js",
103
106
  "types": "./types/index.d.ts",
@@ -1,7 +1,8 @@
1
1
  declare module 'mongoose' {
2
2
  import mongodb = require('mongodb');
3
3
 
4
- interface AggregateOptions {
4
+ interface AggregateOptions extends
5
+ SessionOption {
5
6
  /**
6
7
  * If true, the MongoDB server will use the hard drive to store data during this aggregation.
7
8
  */
@@ -56,8 +57,6 @@ declare module 'mongoose' {
56
57
  * The preferred read preference.
57
58
  */
58
59
  readPreference?: mongodb.ReadPreferenceLike;
59
- /** The ClientSession for this aggregation */
60
- session?: mongodb.ClientSession;
61
60
  /**
62
61
  * Specifies the write concern.
63
62
  */
@@ -65,7 +64,7 @@ declare module 'mongoose' {
65
64
  [key: string]: any;
66
65
  }
67
66
 
68
- class Aggregate<R> {
67
+ class Aggregate<R> implements SessionOperation {
69
68
  /**
70
69
  * Returns an asyncIterator for use with [`for/await/of` loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js
71
70
  * You do not need to call this function explicitly, the JavaScript runtime
@@ -0,0 +1,8 @@
1
+ declare module 'mongoose' {
2
+ type CallbackError = NativeError | null;
3
+
4
+ type Callback<T = any> = (error: CallbackError, result: T) => void;
5
+
6
+ type CallbackWithoutResult = (error: CallbackError) => void;
7
+ type CallbackWithoutResultAndOptionalError = (error?: CallbackError) => void;
8
+ }
@@ -0,0 +1,46 @@
1
+ declare module 'mongoose' {
2
+ import mongodb = require('mongodb');
3
+
4
+ /*
5
+ * section collection.js
6
+ * http://mongoosejs.com/docs/api.html#collection-js
7
+ */
8
+ interface CollectionBase<T extends mongodb.Document> extends mongodb.Collection<T> {
9
+ /*
10
+ * Abstract methods. Some of these are already defined on the
11
+ * mongodb.Collection interface so they've been commented out.
12
+ */
13
+ ensureIndex(...args: any[]): any;
14
+ findAndModify(...args: any[]): any;
15
+ getIndexes(...args: any[]): any;
16
+
17
+ /** The collection name */
18
+ collectionName: string;
19
+ /** The Connection instance */
20
+ conn: Connection;
21
+ /** The collection name */
22
+ name: string;
23
+ }
24
+
25
+ /*
26
+ * section drivers/node-mongodb-native/collection.js
27
+ * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-collection-js
28
+ */
29
+ interface Collection<T extends mongodb.Document = mongodb.Document> extends CollectionBase<T> {
30
+ /**
31
+ * Collection constructor
32
+ * @param name name of the collection
33
+ * @param conn A MongooseConnection instance
34
+ * @param opts optional collection options
35
+ */
36
+ // eslint-disable-next-line @typescript-eslint/no-misused-new
37
+ new(name: string, conn: Connection, opts?: any): Collection<T>;
38
+ /** Formatter for debug print args */
39
+ $format(arg: any, color?: boolean, shell?: boolean): string;
40
+ /** Debug print helper */
41
+ $print(name: string, i: string | number, args: any[], color?: boolean, shell?: boolean): void;
42
+ /** Retrieves information about this collections indexes. */
43
+ getIndexes(): ReturnType<mongodb.Collection<T>['indexInformation']>;
44
+ }
45
+ let Collection: Collection;
46
+ }