mongoose 6.1.9 → 6.2.2

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.
Files changed (76) hide show
  1. package/.eslintrc.json +154 -0
  2. package/CHANGELOG.md +59 -0
  3. package/dist/browser.umd.js +233 -222
  4. package/index.js +5 -1
  5. package/lib/aggregate.js +23 -28
  6. package/lib/browserDocument.js +1 -1
  7. package/lib/cast/number.js +2 -3
  8. package/lib/cast.js +9 -7
  9. package/lib/connection.js +76 -24
  10. package/lib/cursor/AggregationCursor.js +12 -7
  11. package/lib/cursor/QueryCursor.js +11 -6
  12. package/lib/document.js +107 -107
  13. package/lib/drivers/node-mongodb-native/collection.js +12 -4
  14. package/lib/drivers/node-mongodb-native/connection.js +11 -0
  15. package/lib/error/cast.js +3 -2
  16. package/lib/error/index.js +11 -0
  17. package/lib/error/syncIndexes.js +30 -0
  18. package/lib/helpers/clone.js +51 -29
  19. package/lib/helpers/common.js +2 -2
  20. package/lib/helpers/cursor/eachAsync.js +18 -15
  21. package/lib/helpers/document/compile.js +7 -4
  22. package/lib/helpers/getFunctionName.js +6 -4
  23. package/lib/helpers/isMongooseObject.js +9 -8
  24. package/lib/helpers/isObject.js +4 -4
  25. package/lib/helpers/model/discriminator.js +2 -1
  26. package/lib/helpers/path/parentPaths.js +10 -5
  27. package/lib/helpers/populate/assignRawDocsToIdStructure.js +4 -2
  28. package/lib/helpers/populate/assignVals.js +8 -4
  29. package/lib/helpers/populate/getModelsMapForPopulate.js +4 -4
  30. package/lib/helpers/populate/markArraySubdocsPopulated.js +3 -1
  31. package/lib/helpers/populate/modelNamesFromRefPath.js +4 -3
  32. package/lib/helpers/printJestWarning.js +2 -2
  33. package/lib/helpers/projection/applyProjection.js +77 -0
  34. package/lib/helpers/projection/hasIncludedChildren.js +36 -0
  35. package/lib/helpers/projection/isExclusive.js +5 -2
  36. package/lib/helpers/projection/isInclusive.js +5 -1
  37. package/lib/helpers/query/cast$expr.js +279 -0
  38. package/lib/helpers/query/castUpdate.js +6 -2
  39. package/lib/helpers/query/isOperator.js +5 -2
  40. package/lib/helpers/schema/applyPlugins.js +11 -0
  41. package/lib/helpers/schema/getPath.js +4 -2
  42. package/lib/helpers/timestamps/setupTimestamps.js +3 -8
  43. package/lib/index.js +28 -26
  44. package/lib/internal.js +1 -1
  45. package/lib/model.js +161 -122
  46. package/lib/options/SchemaTypeOptions.js +1 -1
  47. package/lib/plugins/trackTransaction.js +5 -4
  48. package/lib/query.js +159 -146
  49. package/lib/queryhelpers.js +10 -10
  50. package/lib/schema/SubdocumentPath.js +4 -3
  51. package/lib/schema/array.js +30 -21
  52. package/lib/schema/buffer.js +1 -1
  53. package/lib/schema/date.js +1 -1
  54. package/lib/schema/decimal128.js +1 -1
  55. package/lib/schema/documentarray.js +9 -11
  56. package/lib/schema/number.js +1 -1
  57. package/lib/schema/objectid.js +2 -2
  58. package/lib/schema/string.js +4 -4
  59. package/lib/schema.js +9 -8
  60. package/lib/schematype.js +77 -30
  61. package/lib/types/ArraySubdocument.js +2 -1
  62. package/lib/types/DocumentArray/index.js +10 -27
  63. package/lib/types/DocumentArray/isMongooseDocumentArray.js +5 -0
  64. package/lib/types/DocumentArray/methods/index.js +15 -3
  65. package/lib/types/array/index.js +22 -21
  66. package/lib/types/array/isMongooseArray.js +5 -0
  67. package/lib/types/array/methods/index.js +22 -23
  68. package/lib/types/buffer.js +3 -3
  69. package/lib/types/map.js +2 -3
  70. package/lib/utils.js +10 -7
  71. package/package.json +19 -151
  72. package/tools/repl.js +1 -1
  73. package/tsconfig.json +8 -0
  74. package/types/PipelineStage.d.ts +272 -0
  75. package/{index.d.ts → types/index.d.ts} +156 -357
  76. package/lib/types/array/ArrayWrapper.js +0 -981
@@ -26,7 +26,11 @@ module.exports = function isInclusive(projection) {
26
26
  // If field is truthy (1, true, etc.) and not an object, then this
27
27
  // projection must be inclusive. If object, assume its $meta, $slice, etc.
28
28
  if (isDefiningProjection(projection[prop]) && !!projection[prop]) {
29
- return true;
29
+ if (projection[prop] != null && typeof projection[prop] === 'object') {
30
+ return isInclusive(projection[prop]);
31
+ } else {
32
+ return !!projection[prop];
33
+ }
30
34
  }
31
35
  }
32
36
 
@@ -0,0 +1,279 @@
1
+ 'use strict';
2
+
3
+ const CastError = require('../../error/cast');
4
+ const StrictModeError = require('../../error/strict');
5
+ const castNumber = require('../../cast/number');
6
+
7
+ const booleanComparison = new Set(['$and', '$or', '$not']);
8
+ const comparisonOperator = new Set(['$cmp', '$eq', '$lt', '$lte', '$gt', '$gte']);
9
+ const arithmeticOperatorArray = new Set([
10
+ // avoid casting '$add' or '$subtract', because expressions can be either number or date,
11
+ // and we don't have a good way of inferring which arguments should be numbers and which should
12
+ // be dates.
13
+ '$multiply',
14
+ '$divide',
15
+ '$log',
16
+ '$mod',
17
+ '$trunc',
18
+ '$avg',
19
+ '$max',
20
+ '$min',
21
+ '$stdDevPop',
22
+ '$stdDevSamp',
23
+ '$sum'
24
+ ]);
25
+ const arithmeticOperatorNumber = new Set([
26
+ '$abs',
27
+ '$exp',
28
+ '$ceil',
29
+ '$floor',
30
+ '$ln',
31
+ '$log10',
32
+ '$round',
33
+ '$sqrt',
34
+ '$sin',
35
+ '$cos',
36
+ '$tan',
37
+ '$asin',
38
+ '$acos',
39
+ '$atan',
40
+ '$atan2',
41
+ '$asinh',
42
+ '$acosh',
43
+ '$atanh',
44
+ '$sinh',
45
+ '$cosh',
46
+ '$tanh',
47
+ '$degreesToRadians',
48
+ '$radiansToDegrees'
49
+ ]);
50
+ const arrayElementOperators = new Set([
51
+ '$arrayElemAt',
52
+ '$first',
53
+ '$last'
54
+ ]);
55
+ const dateOperators = new Set([
56
+ '$year',
57
+ '$month',
58
+ '$week',
59
+ '$dayOfMonth',
60
+ '$dayOfYear',
61
+ '$hour',
62
+ '$minute',
63
+ '$second',
64
+ '$isoDayOfWeek',
65
+ '$isoWeekYear',
66
+ '$isoWeek',
67
+ '$millisecond'
68
+ ]);
69
+
70
+ module.exports = function cast$expr(val, schema, strictQuery) {
71
+ if (typeof val !== 'object' || val === null) {
72
+ throw new Error('`$expr` must be an object');
73
+ }
74
+
75
+ return _castExpression(val, schema, strictQuery);
76
+ };
77
+
78
+ function _castExpression(val, schema, strictQuery) {
79
+ if (isPath(val)) {
80
+ // Assume path
81
+ return val;
82
+ }
83
+
84
+ if (val.$cond != null) {
85
+ if (Array.isArray(val.$cond)) {
86
+ val.$cond = val.$cond.map(expr => _castExpression(expr, schema, strictQuery));
87
+ } else {
88
+ val.$cond.if = _castExpression(val.$cond.if, schema, strictQuery);
89
+ val.$cond.then = _castExpression(val.$cond.then, schema, strictQuery);
90
+ val.$cond.else = _castExpression(val.$cond.else, schema, strictQuery);
91
+ }
92
+ } else if (val.$ifNull != null) {
93
+ val.$ifNull.map(v => _castExpression(v, schema, strictQuery));
94
+ } else if (val.$switch != null) {
95
+ val.branches.map(v => _castExpression(v, schema, strictQuery));
96
+ val.default = _castExpression(val.default, schema, strictQuery);
97
+ }
98
+
99
+ const keys = Object.keys(val);
100
+ for (const key of keys) {
101
+ if (booleanComparison.has(key)) {
102
+ val[key] = val[key].map(v => _castExpression(v, schema, strictQuery));
103
+ } else if (comparisonOperator.has(key)) {
104
+ val[key] = castComparison(val[key], schema, strictQuery);
105
+ } else if (arithmeticOperatorArray.has(key)) {
106
+ val[key] = castArithmetic(val[key], schema, strictQuery);
107
+ } else if (arithmeticOperatorNumber.has(key)) {
108
+ val[key] = castNumberOperator(val[key], schema, strictQuery);
109
+ }
110
+ }
111
+
112
+ if (val.$in) {
113
+ val.$in = castIn(val.$in, schema, strictQuery);
114
+ }
115
+ if (val.$size) {
116
+ val.$size = castNumberOperator(val.$size, schema, strictQuery);
117
+ }
118
+
119
+ _omitUndefined(val);
120
+
121
+ return val;
122
+ }
123
+
124
+ function _omitUndefined(val) {
125
+ const keys = Object.keys(val);
126
+ for (let i = 0, len = keys.length; i < len; ++i) {
127
+ (val[keys[i]] === void 0) && delete val[keys[i]];
128
+ }
129
+ }
130
+
131
+ // { $op: <number> }
132
+ function castNumberOperator(val) {
133
+ if (!isLiteral(val)) {
134
+ return val;
135
+ }
136
+
137
+ try {
138
+ return castNumber(val);
139
+ } catch (err) {
140
+ throw new CastError('Number', val);
141
+ }
142
+ }
143
+
144
+ function castIn(val, schema, strictQuery) {
145
+ const path = val[1];
146
+ if (!isPath(path)) {
147
+ return val;
148
+ }
149
+ const search = val[0];
150
+
151
+ const schematype = schema.path(path.slice(1));
152
+ if (schematype === null) {
153
+ if (strictQuery === false) {
154
+ return val;
155
+ } else if (strictQuery === 'throw') {
156
+ throw new StrictModeError('$in');
157
+ }
158
+
159
+ return void 0;
160
+ }
161
+
162
+ if (!schematype.$isMongooseArray) {
163
+ throw new Error('Path must be an array for $in');
164
+ }
165
+
166
+ return [
167
+ schematype.$isMongooseDocumentArray ? schematype.$embeddedSchemaType.cast(search) : schematype.caster.cast(search),
168
+ path
169
+ ];
170
+ }
171
+
172
+ // { $op: [<number>, <number>] }
173
+ function castArithmetic(val) {
174
+ if (!Array.isArray(val)) {
175
+ if (!isLiteral(val)) {
176
+ return val;
177
+ }
178
+ try {
179
+ return castNumber(val);
180
+ } catch (err) {
181
+ throw new CastError('Number', val);
182
+ }
183
+ }
184
+
185
+ return val.map(v => {
186
+ if (!isLiteral(v)) {
187
+ return v;
188
+ }
189
+ try {
190
+ return castNumber(v);
191
+ } catch (err) {
192
+ throw new CastError('Number', v);
193
+ }
194
+ });
195
+ }
196
+
197
+ // { $op: [expression, expression] }
198
+ function castComparison(val, schema, strictQuery) {
199
+ if (!Array.isArray(val) || val.length !== 2) {
200
+ throw new Error('Comparison operator must be an array of length 2');
201
+ }
202
+
203
+ val[0] = _castExpression(val[0], schema, strictQuery);
204
+ const lhs = val[0];
205
+
206
+ if (isLiteral(val[1])) {
207
+ let path = null;
208
+ let schematype = null;
209
+ let caster = null;
210
+ if (isPath(lhs)) {
211
+ path = lhs.slice(1);
212
+ schematype = schema.path(path);
213
+ } else if (typeof lhs === 'object' && lhs != null) {
214
+ for (const key of Object.keys(lhs)) {
215
+ if (dateOperators.has(key) && isPath(lhs[key])) {
216
+ path = lhs[key].slice(1) + '.' + key;
217
+ caster = castNumber;
218
+ } else if (arrayElementOperators.has(key) && isPath(lhs[key])) {
219
+ path = lhs[key].slice(1) + '.' + key;
220
+ schematype = schema.path(lhs[key].slice(1));
221
+ if (schematype != null) {
222
+ if (schematype.$isMongooseDocumentArray) {
223
+ schematype = schematype.$embeddedSchemaType;
224
+ } else if (schematype.$isMongooseArray) {
225
+ schematype = schematype.caster;
226
+ }
227
+ }
228
+ }
229
+ }
230
+ }
231
+
232
+ const is$literal = typeof val[1] === 'object' && val[1] != null && val[1].$literal != null;
233
+ if (schematype != null) {
234
+ if (is$literal) {
235
+ val[1] = { $literal: schematype.cast(val[1].$literal) };
236
+ } else {
237
+ val[1] = schematype.cast(val[1]);
238
+ }
239
+ } else if (caster != null) {
240
+ if (is$literal) {
241
+ try {
242
+ val[1] = { $literal: caster(val[1].$literal) };
243
+ } catch (err) {
244
+ throw new CastError(caster.name.replace(/^cast/, ''), val[1], path + '.$literal');
245
+ }
246
+ } else {
247
+ try {
248
+ val[1] = caster(val[1]);
249
+ } catch (err) {
250
+ throw new CastError(caster.name.replace(/^cast/, ''), val[1], path);
251
+ }
252
+ }
253
+ } else if (path != null && strictQuery === true) {
254
+ return void 0;
255
+ } else if (path != null && strictQuery === 'throw') {
256
+ throw new StrictModeError(path);
257
+ }
258
+ } else {
259
+ val[1] = _castExpression(val[1]);
260
+ }
261
+
262
+ return val;
263
+ }
264
+
265
+ function isPath(val) {
266
+ return typeof val === 'string' && val[0] === '$';
267
+ }
268
+
269
+ function isLiteral(val) {
270
+ if (typeof val === 'string' && val[0] === '$') {
271
+ return false;
272
+ }
273
+ if (typeof val === 'object' && val !== null && Object.keys(val).find(key => key[0] === '$')) {
274
+ // The `$literal` expression can make an object a literal
275
+ // https://docs.mongodb.com/manual/reference/operator/aggregation/literal/#mongodb-expression-exp.-literal
276
+ return val.$literal != null;
277
+ }
278
+ return true;
279
+ }
@@ -41,9 +41,10 @@ module.exports = function castUpdate(schema, obj, options, context, filter) {
41
41
  }
42
42
  return obj;
43
43
  }
44
+
44
45
  if (schema.options.strict === 'throw' && obj.hasOwnProperty(schema.options.discriminatorKey)) {
45
46
  throw new StrictModeError(schema.options.discriminatorKey);
46
- } else if (context._mongooseOptions != null && !context._mongooseOptions.overwriteDiscriminatorKey) {
47
+ } else if (!options.overwriteDiscriminatorKey) {
47
48
  delete obj[schema.options.discriminatorKey];
48
49
  }
49
50
  if (options.upsert) {
@@ -353,7 +354,10 @@ function walkUpdatePath(schema, obj, op, options, context, filter, pref) {
353
354
  }
354
355
 
355
356
  if (Array.isArray(obj[key]) && (op === '$addToSet' || op === '$push') && key !== '$each') {
356
- if (schematype && schematype.caster && !schematype.caster.$isMongooseArray) {
357
+ if (schematype &&
358
+ schematype.caster &&
359
+ !schematype.caster.$isMongooseArray &&
360
+ !schematype.caster[schemaMixedSymbol]) {
357
361
  obj[key] = { $each: obj[key] };
358
362
  }
359
363
  }
@@ -7,5 +7,8 @@ const specialKeys = new Set([
7
7
  ]);
8
8
 
9
9
  module.exports = function isOperator(path) {
10
- return path.startsWith('$') && !specialKeys.has(path);
11
- };
10
+ return (
11
+ path[0] === '$' &&
12
+ !specialKeys.has(path)
13
+ );
14
+ };
@@ -7,7 +7,18 @@ module.exports = function applyPlugins(schema, plugins, options, cacheKey) {
7
7
  schema[cacheKey] = true;
8
8
 
9
9
  if (!options || !options.skipTopLevel) {
10
+ let pluginTags = null;
10
11
  for (const plugin of plugins) {
12
+ const tags = plugin[1] == null ? null : plugin[1].tags;
13
+ if (!Array.isArray(tags)) {
14
+ schema.plugin(plugin[0], plugin[1]);
15
+ continue;
16
+ }
17
+
18
+ pluginTags = pluginTags || new Set(schema.options.pluginTags || []);
19
+ if (!tags.find(tag => pluginTags.has(tag))) {
20
+ continue;
21
+ }
11
22
  schema.plugin(plugin[0], plugin[1]);
12
23
  }
13
24
  }
@@ -5,6 +5,8 @@
5
5
  * needing to put `.0.`, so `getPath(schema, 'docArr.elProp')` works.
6
6
  */
7
7
 
8
+ const numberRE = /^\d+$/;
9
+
8
10
  module.exports = function getPath(schema, path) {
9
11
  let schematype = schema.path(path);
10
12
  if (schematype != null) {
@@ -16,7 +18,7 @@ module.exports = function getPath(schema, path) {
16
18
  let isArray = false;
17
19
 
18
20
  for (const piece of pieces) {
19
- if (/^\d+$/.test(piece) && isArray) {
21
+ if (isArray && numberRE.test(piece)) {
20
22
  continue;
21
23
  }
22
24
  cur = cur.length === 0 ? piece : cur + '.' + piece;
@@ -25,7 +27,7 @@ module.exports = function getPath(schema, path) {
25
27
  if (schematype != null && schematype.schema) {
26
28
  schema = schematype.schema;
27
29
  cur = '';
28
- if (schematype.$isMongooseDocumentArray) {
30
+ if (!isArray && schematype.$isMongooseDocumentArray) {
29
31
  isArray = true;
30
32
  }
31
33
  }
@@ -47,20 +47,15 @@ module.exports = function setupTimestamps(schema, timestamps) {
47
47
  const defaultTimestamp = currentTime != null ?
48
48
  currentTime() :
49
49
  this.ownerDocument().constructor.base.now();
50
- const auto_id = this._id && this._id.auto;
51
50
 
52
51
  if (!skipCreatedAt && this.isNew && createdAt && !this.$__getValue(createdAt) && this.$__isSelected(createdAt)) {
53
- this.$set(createdAt, auto_id ? this._id.getTimestamp() : defaultTimestamp);
52
+ this.$set(createdAt, defaultTimestamp);
54
53
  }
55
54
 
56
55
  if (!skipUpdatedAt && updatedAt && (this.isNew || this.$isModified())) {
57
56
  let ts = defaultTimestamp;
58
- if (this.isNew) {
59
- if (createdAt != null) {
60
- ts = this.$__getValue(createdAt);
61
- } else if (auto_id) {
62
- ts = this._id.getTimestamp();
63
- }
57
+ if (this.isNew && createdAt != null) {
58
+ ts = this.$__getValue(createdAt);
64
59
  }
65
60
  this.$set(updatedAt, ts);
66
61
  }
package/lib/index.js CHANGED
@@ -19,7 +19,6 @@ const Query = require('./query');
19
19
  const Model = require('./model');
20
20
  const applyPlugins = require('./helpers/schema/applyPlugins');
21
21
  const driver = require('./driver');
22
- const get = require('./helpers/get');
23
22
  const promiseOrCallback = require('./helpers/promiseOrCallback');
24
23
  const legacyPluralize = require('./helpers/pluralize');
25
24
  const utils = require('./utils');
@@ -252,17 +251,17 @@ Mongoose.prototype.get = Mongoose.prototype.set;
252
251
  * db.openUri('localhost', 'database', port, [opts]);
253
252
  *
254
253
  * @param {String} [uri] a mongodb:// URI
255
- * @param {Object} [options] passed down to the [MongoDB driver's `connect()` function](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html), except for 4 mongoose-specific options explained below.
256
- * @param {Boolean} [options.bufferCommands=true] Mongoose specific option. Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection.
254
+ * @param {Object} [options] passed down to the [MongoDB driver's `connect()` function](https://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html), except for 4 mongoose-specific options explained below.
255
+ * @param {Boolean} [options.bufferCommands=true] Mongoose specific option. Set to false to [disable buffering](https://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection.
257
256
  * @param {String} [options.dbName] The name of the database you want to use. If not provided, Mongoose uses the database name from connection string.
258
257
  * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility.
259
258
  * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility.
260
259
  * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.
261
260
  * @param {Number} [options.reconnectTries=30] If you're connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every `reconnectInterval` milliseconds for `reconnectTries` times, and give up afterward. When the driver gives up, the mongoose connection emits a `reconnectFailed` event. This option does nothing for replica set connections.
262
261
  * @param {Number} [options.reconnectInterval=1000] See `reconnectTries` option above.
263
- * @param {Class} [options.promiseLibrary] Sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html).
264
- * @param {Number} [options.maxPoolSize=5] The maximum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs).
265
- * @param {Number} [options.minPoolSize=1] The minimum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs).
262
+ * @param {Class} [options.promiseLibrary] Sets the [underlying driver's promise library](https://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html).
263
+ * @param {Number} [options.maxPoolSize=5] The maximum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](https://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs).
264
+ * @param {Number} [options.minPoolSize=1] The minimum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](https://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs).
266
265
  * @param {Number} [options.connectTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _during initial connection_. Defaults to 30000. This option is passed transparently to [Node.js' `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback).
267
266
  * @param {Number} [options.socketTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _after initial connection_. A socket may be inactive because of either no activity or a long-running operation. This is set to `30000` by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes.
268
267
  * @param {Number} [options.family=0] Passed transparently to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. May be either `0`, `4`, or `6`. `4` means use IPv4 only, `6` means use IPv6 only, `0` means try both.
@@ -309,20 +308,20 @@ Mongoose.prototype.createConnection = function(uri, options, callback) {
309
308
  * })
310
309
  *
311
310
  * @param {String} uri(s)
312
- * @param {Object} [options] passed down to the [MongoDB driver's `connect()` function](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html), except for 4 mongoose-specific options explained below.
313
- * @param {Boolean} [options.bufferCommands=true] Mongoose specific option. Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection.
311
+ * @param {Object} [options] passed down to the [MongoDB driver's `connect()` function](https://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html), except for 4 mongoose-specific options explained below.
312
+ * @param {Boolean} [options.bufferCommands=true] Mongoose specific option. Set to false to [disable buffering](https://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection.
314
313
  * @param {Number} [options.bufferTimeoutMS=10000] Mongoose specific option. If `bufferCommands` is true, Mongoose will throw an error after `bufferTimeoutMS` if the operation is still buffered.
315
314
  * @param {String} [options.dbName] The name of the database we want to use. If not provided, use database name from connection string.
316
315
  * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility.
317
316
  * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility.
318
- * @param {Number} [options.maxPoolSize=100] The maximum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs).
317
+ * @param {Number} [options.maxPoolSize=100] The maximum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](https://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs).
319
318
  * @param {Number} [options.minPoolSize=0] The minimum number of sockets the MongoDB driver will keep open for this connection.
320
319
  * @param {Number} [options.serverSelectionTimeoutMS] If `useUnifiedTopology = true`, the MongoDB driver will try to find a server to send any given operation to, and keep retrying for `serverSelectionTimeoutMS` milliseconds before erroring out. If not set, the MongoDB driver defaults to using `30000` (30 seconds).
321
320
  * @param {Number} [options.heartbeatFrequencyMS] If `useUnifiedTopology = true`, the MongoDB driver sends a heartbeat every `heartbeatFrequencyMS` to check on the status of the connection. A heartbeat is subject to `serverSelectionTimeoutMS`, so the MongoDB driver will retry failed heartbeats for up to 30 seconds by default. Mongoose only emits a `'disconnected'` event after a heartbeat has failed, so you may want to decrease this setting to reduce the time between when your server goes down and when Mongoose emits `'disconnected'`. We recommend you do **not** set this setting below 1000, too many heartbeats can lead to performance degradation.
322
321
  * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.
323
322
  * @param {Number} [options.reconnectTries=30] If you're connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every `reconnectInterval` milliseconds for `reconnectTries` times, and give up afterward. When the driver gives up, the mongoose connection emits a `reconnectFailed` event. This option does nothing for replica set connections.
324
323
  * @param {Number} [options.reconnectInterval=1000] See `reconnectTries` option above.
325
- * @param {Class} [options.promiseLibrary] Sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html).
324
+ * @param {Class} [options.promiseLibrary] Sets the [underlying driver's promise library](https://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html).
326
325
  * @param {Number} [options.connectTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _during initial connection_. Defaults to 30000. This option is passed transparently to [Node.js' `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback).
327
326
  * @param {Number} [options.socketTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _after initial connection_. A socket may be inactive because of either no activity or a long-running operation. This is set to `30000` by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes.
328
327
  * @param {Number} [options.family=0] Passed transparently to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. May be either `0`, `4`, or `6`. `4` means use IPv4 only, `6` means use IPv6 only, `0` means try both.
@@ -379,13 +378,13 @@ Mongoose.prototype.disconnect = function(callback) {
379
378
  /**
380
379
  * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions)
381
380
  * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/),
382
- * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
381
+ * and [transactions](https://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
383
382
  *
384
383
  * Calling `mongoose.startSession()` is equivalent to calling `mongoose.connection.startSession()`.
385
384
  * Sessions are scoped to a connection, so calling `mongoose.startSession()`
386
385
  * starts a session on the [default mongoose connection](/docs/api.html#mongoose_Mongoose-connection).
387
386
  *
388
- * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession)
387
+ * @param {Object} [options] see the [mongodb driver options](https://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession)
389
388
  * @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency
390
389
  * @param {Function} [callback]
391
390
  * @return {Promise<ClientSession>} promise that resolves to a MongoDB driver `ClientSession`
@@ -632,10 +631,8 @@ Mongoose.prototype._applyPlugins = function(schema, options) {
632
631
  const _mongoose = this instanceof Mongoose ? this : mongoose;
633
632
 
634
633
  options = options || {};
635
- options.applyPluginsToDiscriminators = get(_mongoose,
636
- 'options.applyPluginsToDiscriminators', false);
637
- options.applyPluginsToChildSchemas = get(_mongoose,
638
- 'options.applyPluginsToChildSchemas', true);
634
+ options.applyPluginsToDiscriminators = _mongoose.options && _mongoose.options.applyPluginsToDiscriminators || false;
635
+ options.applyPluginsToChildSchemas = typeof (_mongoose.options && _mongoose.options.applyPluginsToDiscriminators) === 'boolean' ? _mongoose.options.applyPluginsToDiscriminators : true;
639
636
  applyPlugins(schema, _mongoose.plugins, options, '$globalPluginsApplied');
640
637
  };
641
638
 
@@ -951,28 +948,33 @@ Mongoose.prototype.ObjectId = SchemaTypes.ObjectId;
951
948
  * mongoose.isValidObjectId({ test: 42 }); // false
952
949
  *
953
950
  * @method isValidObjectId
951
+ * @param {Any} value
952
+ * @returns {boolean} true if it is a valid ObjectId
954
953
  * @api public
955
954
  */
956
955
 
957
956
  Mongoose.prototype.isValidObjectId = function(v) {
958
- try {
959
- new this.Types.ObjectId(v);
960
- } catch (err) {
961
- return false;
962
- }
963
-
964
- return true;
957
+ const _mongoose = this instanceof Mongoose ? this : mongoose;
958
+ return _mongoose.Types.ObjectId.isValid(v);
965
959
  };
966
960
 
967
- Mongoose.prototype.syncIndexes = function() {
961
+ /**
962
+ *
963
+ * Syncs all the indexes for the models registered with this connection.
964
+ *
965
+ * @param {Object} options
966
+ * @param {Boolean} options.continueOnError `false` by default. If set to `true`, mongoose will not throw an error if one model syncing failed, and will return an object where the keys are the names of the models, and the values are the results/errors for each model.
967
+ * @returns
968
+ */
969
+ Mongoose.prototype.syncIndexes = function(options) {
968
970
  const _mongoose = this instanceof Mongoose ? this : mongoose;
969
- return _mongoose.connection.syncIndexes();
971
+ return _mongoose.connection.syncIndexes(options);
970
972
  };
971
973
 
972
974
  /**
973
975
  * The Mongoose Decimal128 [SchemaType](/docs/schematypes.html). Used for
974
976
  * declaring paths in your schema that should be
975
- * [128-bit decimal floating points](http://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-decimal.html).
977
+ * [128-bit decimal floating points](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-decimal.html).
976
978
  * Do not use this to create a new Decimal128 instance, use `mongoose.Types.Decimal128`
977
979
  * instead.
978
980
  *
package/lib/internal.js CHANGED
@@ -10,7 +10,7 @@ const ActiveRoster = StateMachine.ctor('require', 'modify', 'init', 'default', '
10
10
  module.exports = exports = InternalCache;
11
11
 
12
12
  function InternalCache() {
13
- this.activePaths = new ActiveRoster;
13
+ this.activePaths = new ActiveRoster();
14
14
  this.strictMode = undefined;
15
15
  }
16
16