mongoose 8.8.3 → 8.9.0

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.
@@ -0,0 +1,249 @@
1
+ 'use strict';
2
+
3
+ /*!
4
+ * Module dependencies.
5
+ */
6
+
7
+ const CastError = require('../error/cast');
8
+ const SchemaType = require('../schemaType');
9
+ const castInt32 = require('../cast/int32');
10
+
11
+ /**
12
+ * Int32 SchemaType constructor.
13
+ *
14
+ * @param {String} path
15
+ * @param {Object} options
16
+ * @inherits SchemaType
17
+ * @api public
18
+ */
19
+
20
+ function SchemaInt32(path, options) {
21
+ SchemaType.call(this, path, options, 'Int32');
22
+ }
23
+
24
+ /**
25
+ * This schema type's name, to defend against minifiers that mangle
26
+ * function names.
27
+ *
28
+ * @api public
29
+ */
30
+ SchemaInt32.schemaName = 'Int32';
31
+
32
+ SchemaInt32.defaultOptions = {};
33
+
34
+ /*!
35
+ * Inherits from SchemaType.
36
+ */
37
+ SchemaInt32.prototype = Object.create(SchemaType.prototype);
38
+ SchemaInt32.prototype.constructor = SchemaInt32;
39
+
40
+ /*!
41
+ * ignore
42
+ */
43
+
44
+ SchemaInt32._cast = castInt32;
45
+
46
+ /**
47
+ * Sets a default option for all Int32 instances.
48
+ *
49
+ * #### Example:
50
+ *
51
+ * // Make all Int32 fields required by default
52
+ * mongoose.Schema.Int32.set('required', true);
53
+ *
54
+ * @param {String} option The option you'd like to set the value for
55
+ * @param {Any} value value for option
56
+ * @return {undefined}
57
+ * @function set
58
+ * @static
59
+ * @api public
60
+ */
61
+
62
+ SchemaInt32.set = SchemaType.set;
63
+
64
+ SchemaInt32.setters = [];
65
+
66
+ /**
67
+ * Attaches a getter for all Int32 instances
68
+ *
69
+ * #### Example:
70
+ *
71
+ * // Converts int32 to be a represent milliseconds upon access
72
+ * mongoose.Schema.Int32.get(v => v == null ? '0 ms' : v.toString() + ' ms');
73
+ *
74
+ * @param {Function} getter
75
+ * @return {this}
76
+ * @function get
77
+ * @static
78
+ * @api public
79
+ */
80
+
81
+ SchemaInt32.get = SchemaType.get;
82
+
83
+ /*!
84
+ * ignore
85
+ */
86
+
87
+ SchemaInt32._defaultCaster = v => {
88
+ const INT32_MAX = 0x7FFFFFFF;
89
+ const INT32_MIN = -0x80000000;
90
+
91
+ if (v != null) {
92
+ if (typeof v !== 'number' || v !== (v | 0) || v < INT32_MIN || v > INT32_MAX) {
93
+ throw new Error();
94
+ }
95
+ }
96
+
97
+ return v;
98
+ };
99
+
100
+ /**
101
+ * Get/set the function used to cast arbitrary values to 32-bit integers
102
+ *
103
+ * #### Example:
104
+ *
105
+ * // Make Mongoose cast NaN to 0
106
+ * const defaultCast = mongoose.Schema.Types.Int32.cast();
107
+ * mongoose.Schema.Types.Int32.cast(v => {
108
+ * if (isNaN(v)) {
109
+ * return 0;
110
+ * }
111
+ * return defaultCast(v);
112
+ * });
113
+ *
114
+ * // Or disable casting for Int32s entirely (only JS numbers within 32-bit integer bounds and null-ish values are permitted)
115
+ * mongoose.Schema.Int32.cast(false);
116
+ *
117
+ *
118
+ * @param {Function} caster
119
+ * @return {Function}
120
+ * @function get
121
+ * @static
122
+ * @api public
123
+ */
124
+
125
+ SchemaInt32.cast = function cast(caster) {
126
+ if (arguments.length === 0) {
127
+ return this._cast;
128
+ }
129
+ if (caster === false) {
130
+ caster = this._defaultCaster;
131
+ }
132
+
133
+ this._cast = caster;
134
+
135
+ return this._cast;
136
+ };
137
+
138
+
139
+ /*!
140
+ * ignore
141
+ */
142
+
143
+ SchemaInt32._checkRequired = v => v != null;
144
+ /**
145
+ * Override the function the required validator uses to check whether a value
146
+ * passes the `required` check.
147
+ *
148
+ * @param {Function} fn
149
+ * @return {Function}
150
+ * @function checkRequired
151
+ * @static
152
+ * @api public
153
+ */
154
+
155
+ SchemaInt32.checkRequired = SchemaType.checkRequired;
156
+
157
+ /**
158
+ * Check if the given value satisfies a required validator.
159
+ *
160
+ * @param {Any} value
161
+ * @return {Boolean}
162
+ * @api public
163
+ */
164
+
165
+ SchemaInt32.prototype.checkRequired = function(value) {
166
+ return this.constructor._checkRequired(value);
167
+ };
168
+
169
+ /**
170
+ * Casts to Int32
171
+ *
172
+ * @param {Object} value
173
+ * @param {Object} model this value is optional
174
+ * @api private
175
+ */
176
+
177
+ SchemaInt32.prototype.cast = function(value) {
178
+ let castInt32;
179
+ if (typeof this._castFunction === 'function') {
180
+ castInt32 = this._castFunction;
181
+ } else if (typeof this.constructor.cast === 'function') {
182
+ castInt32 = this.constructor.cast();
183
+ } else {
184
+ castInt32 = SchemaInt32.cast();
185
+ }
186
+
187
+ try {
188
+ return castInt32(value);
189
+ } catch (error) {
190
+ throw new CastError('Int32', value, this.path, error, this);
191
+ }
192
+ };
193
+
194
+ /*!
195
+ * ignore
196
+ */
197
+
198
+ SchemaInt32.$conditionalHandlers = {
199
+ ...SchemaType.prototype.$conditionalHandlers,
200
+ $gt: handleSingle,
201
+ $gte: handleSingle,
202
+ $lt: handleSingle,
203
+ $lte: handleSingle
204
+ };
205
+
206
+ /*!
207
+ * ignore
208
+ */
209
+
210
+ function handleSingle(val, context) {
211
+ return this.castForQuery(null, val, context);
212
+ }
213
+
214
+ /**
215
+ * Casts contents for queries.
216
+ *
217
+ * @param {String} $conditional
218
+ * @param {any} val
219
+ * @api private
220
+ */
221
+
222
+ SchemaInt32.prototype.castForQuery = function($conditional, val, context) {
223
+ let handler;
224
+ if ($conditional != null) {
225
+ handler = SchemaInt32.$conditionalHandlers[$conditional];
226
+
227
+ if (handler) {
228
+ return handler.call(this, val);
229
+ }
230
+
231
+ return this.applySetters(null, val, context);
232
+ }
233
+
234
+ try {
235
+ return this.applySetters(val, context);
236
+ } catch (err) {
237
+ if (err instanceof CastError && err.path === this.path && this.$fullPath != null) {
238
+ err.path = this.$fullPath;
239
+ }
240
+ throw err;
241
+ }
242
+ };
243
+
244
+
245
+ /*!
246
+ * Module exports.
247
+ */
248
+
249
+ module.exports = SchemaInt32;
package/lib/schema.js CHANGED
@@ -2810,6 +2810,39 @@ Schema.prototype._getPathType = function(path) {
2810
2810
  return search(path.split('.'), _this);
2811
2811
  };
2812
2812
 
2813
+ /**
2814
+ * Transforms the duplicate key error by checking for duplicate key error messages by path.
2815
+ * If no duplicate key error messages are found, returns the original error.
2816
+ *
2817
+ * @param {Error} error The error to transform
2818
+ * @returns {Error} The transformed error
2819
+ * @api private
2820
+ */
2821
+
2822
+ Schema.prototype._transformDuplicateKeyError = function _transformDuplicateKeyError(error) {
2823
+ if (!this._duplicateKeyErrorMessagesByPath) {
2824
+ return error;
2825
+ }
2826
+ if (error.code !== 11000 && error.code !== 11001) {
2827
+ return error;
2828
+ }
2829
+
2830
+ if (error.keyPattern != null) {
2831
+ const keyPattern = error.keyPattern;
2832
+ const keys = Object.keys(keyPattern);
2833
+ if (keys.length !== 1) {
2834
+ return error;
2835
+ }
2836
+ const firstKey = keys[0];
2837
+ if (!this._duplicateKeyErrorMessagesByPath.hasOwnProperty(firstKey)) {
2838
+ return error;
2839
+ }
2840
+ return new MongooseError(this._duplicateKeyErrorMessagesByPath[firstKey], { cause: error });
2841
+ }
2842
+
2843
+ return error;
2844
+ };
2845
+
2813
2846
  /*!
2814
2847
  * ignore
2815
2848
  */
@@ -2859,6 +2892,8 @@ module.exports = exports = Schema;
2859
2892
  * - [Mixed](https://mongoosejs.com/docs/schematypes.html#mixed)
2860
2893
  * - [UUID](https://mongoosejs.com/docs/schematypes.html#uuid)
2861
2894
  * - [BigInt](https://mongoosejs.com/docs/schematypes.html#bigint)
2895
+ * - [Double] (https://mongoosejs.com/docs/schematypes.html#double)
2896
+ * - [Int32](https://mongoosejs.com/docs/schematypes.html#int32)
2862
2897
  *
2863
2898
  * Using this exposed access to the `Mixed` SchemaType, we can use them in our schema.
2864
2899
  *
package/lib/schemaType.js CHANGED
@@ -74,7 +74,6 @@ function SchemaType(path, options, instance) {
74
74
  this.options = new Options(options);
75
75
  this._index = null;
76
76
 
77
-
78
77
  if (utils.hasUserDefinedProperty(this.options, 'immutable')) {
79
78
  this.$immutable = this.options.immutable;
80
79
 
@@ -447,21 +446,38 @@ SchemaType.prototype.index = function(options) {
447
446
  *
448
447
  * _NOTE: violating the constraint returns an `E11000` error from MongoDB when saving, not a Mongoose validation error._
449
448
  *
450
- * @param {Boolean} bool
449
+ * You can optionally specify an error message to replace MongoDB's default `E11000 duplicate key error` message.
450
+ * The following will throw a "Email must be unique" error if `save()`, `updateOne()`, `updateMany()`, `replaceOne()`,
451
+ * `findOneAndUpdate()`, or `findOneAndReplace()` throws a duplicate key error:
452
+ *
453
+ * ```javascript
454
+ * new Schema({
455
+ * email: {
456
+ * type: String,
457
+ * unique: [true, 'Email must be unique']
458
+ * }
459
+ * });
460
+ * ```
461
+ *
462
+ * Note that the above syntax does **not** work for `bulkWrite()` or `insertMany()`. `bulkWrite()` and `insertMany()`
463
+ * will still throw MongoDB's default `E11000 duplicate key error` message.
464
+ *
465
+ * @param {Boolean} value
466
+ * @param {String} [message]
451
467
  * @return {SchemaType} this
452
468
  * @api public
453
469
  */
454
470
 
455
- SchemaType.prototype.unique = function(bool) {
471
+ SchemaType.prototype.unique = function unique(value, message) {
456
472
  if (this._index === false) {
457
- if (!bool) {
473
+ if (!value) {
458
474
  return;
459
475
  }
460
476
  throw new Error('Path "' + this.path + '" may not have `index` set to ' +
461
477
  'false and `unique` set to true');
462
478
  }
463
479
 
464
- if (!this.options.hasOwnProperty('index') && bool === false) {
480
+ if (!this.options.hasOwnProperty('index') && value === false) {
465
481
  return this;
466
482
  }
467
483
 
@@ -471,7 +487,10 @@ SchemaType.prototype.unique = function(bool) {
471
487
  this._index = { type: this._index };
472
488
  }
473
489
 
474
- this._index.unique = bool;
490
+ this._index.unique = !!value;
491
+ if (typeof message === 'string') {
492
+ this._duplicateKeyErrorMessage = message;
493
+ }
475
494
  return this;
476
495
  };
477
496
 
@@ -1567,8 +1586,9 @@ SchemaType.prototype._castRef = function _castRef(value, doc, init) {
1567
1586
  !doc.$__.populated[path].options ||
1568
1587
  !doc.$__.populated[path].options.options ||
1569
1588
  !doc.$__.populated[path].options.options.lean) {
1570
- ret = new pop.options[populateModelSymbol](value);
1571
- ret.$__.wasPopulated = { value: ret._doc._id };
1589
+ const PopulatedModel = pop ? pop.options[populateModelSymbol] : doc.constructor.db.model(this.options.ref);
1590
+ ret = new PopulatedModel(value);
1591
+ ret.$__.wasPopulated = { value: ret._doc._id, options: { [populateModelSymbol]: PopulatedModel } };
1572
1592
  }
1573
1593
 
1574
1594
  return ret;
@@ -1743,6 +1763,14 @@ SchemaType.prototype.getEmbeddedSchemaType = function getEmbeddedSchemaType() {
1743
1763
  return this.$embeddedSchemaType;
1744
1764
  };
1745
1765
 
1766
+ /*!
1767
+ * If _duplicateKeyErrorMessage is a string, replace unique index errors "E11000 duplicate key error" with this string.
1768
+ *
1769
+ * @api private
1770
+ */
1771
+
1772
+ SchemaType.prototype._duplicateKeyErrorMessage = null;
1773
+
1746
1774
  /*!
1747
1775
  * Module exports.
1748
1776
  */
@@ -17,6 +17,7 @@ const VALID_OPTIONS = Object.freeze([
17
17
  'cloneSchemas',
18
18
  'createInitialConnection',
19
19
  'debug',
20
+ 'forceRepopulate',
20
21
  'id',
21
22
  'timestamps.createdAt.immutable',
22
23
  'maxTimeMS',
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mongoose",
3
3
  "description": "Mongoose MongoDB ODM",
4
- "version": "8.8.3",
4
+ "version": "8.9.0",
5
5
  "author": "Guillermo Rauch <guillermo@learnboost.com>",
6
6
  "keywords": [
7
7
  "mongodb",
@@ -19,9 +19,9 @@
19
19
  ],
20
20
  "license": "MIT",
21
21
  "dependencies": {
22
- "bson": "^6.7.0",
22
+ "bson": "^6.10.1",
23
23
  "kareem": "2.6.3",
24
- "mongodb": "~6.10.0",
24
+ "mongodb": "~6.12.0",
25
25
  "mpath": "0.9.0",
26
26
  "mquery": "5.0.0",
27
27
  "ms": "2.1.3",
@@ -52,8 +52,8 @@
52
52
  "highlight.js": "11.10.0",
53
53
  "lodash.isequal": "4.5.0",
54
54
  "lodash.isequalwith": "4.4.0",
55
- "markdownlint-cli2": "^0.14.0",
56
- "marked": "14.1.3",
55
+ "markdownlint-cli2": "^0.15.0",
56
+ "marked": "15.0.3",
57
57
  "mkdirp": "^3.0.1",
58
58
  "mocha": "10.8.2",
59
59
  "moment": "2.30.1",
@@ -65,8 +65,8 @@
65
65
  "sinon": "19.0.2",
66
66
  "stream-browserify": "3.0.0",
67
67
  "tsd": "0.31.2",
68
- "typescript": "5.6.3",
69
- "uuid": "11.0.2",
68
+ "typescript": "5.7.2",
69
+ "uuid": "11.0.3",
70
70
  "webpack": "5.96.1"
71
71
  },
72
72
  "directories": {
@@ -1150,6 +1150,21 @@ declare module 'mongoose' {
1150
1150
  $first: Expression;
1151
1151
  }
1152
1152
 
1153
+ export interface FirstN {
1154
+ /**
1155
+ * $firstN can be used as an aggregation accumulator or array operator.
1156
+ * As an aggregation accumulator, it returns an aggregation of the first n elements within a group.
1157
+ * As an array operator, it returns the specified number of elements from the beginning of an array.
1158
+ *
1159
+ * @version 5.2
1160
+ * @see https://www.mongodb.com/docs/manual/reference/operator/aggregation/firstN/#mongodb-expression-exp.-first
1161
+ */
1162
+ $firstN: {
1163
+ input: Expression
1164
+ n: Expression,
1165
+ };
1166
+ }
1167
+
1153
1168
  export interface In {
1154
1169
  /**
1155
1170
  * Returns a boolean indicating whether a specified value is in an array.
@@ -1190,6 +1205,21 @@ declare module 'mongoose' {
1190
1205
  $last: Expression;
1191
1206
  }
1192
1207
 
1208
+ export interface LastN {
1209
+ /**
1210
+ * $lastN can be used as an aggregation accumulator or array operator.
1211
+ * As an aggregation accumulator, it an aggregation of the last n elements within a group.
1212
+ * As an array operator, it returns the specified number of elements from the end of an array.
1213
+ *
1214
+ * @version 5.2
1215
+ * @see https://www.mongodb.com/docs/manual/reference/operator/aggregation/lastN/#mongodb-group-grp.-lastN
1216
+ */
1217
+ $lastN: {
1218
+ input: Expression
1219
+ n: Expression,
1220
+ };
1221
+ }
1222
+
1193
1223
  export interface LinearFill {
1194
1224
  /**
1195
1225
  * Fills null and missing fields in a window using linear interpolation based on surrounding field values.
@@ -2000,6 +2030,34 @@ declare module 'mongoose' {
2000
2030
  $avg: Expression;
2001
2031
  }
2002
2032
 
2033
+ export interface Bottom {
2034
+ /**
2035
+ * Returns the bottom element within a group according to the specified sort order.
2036
+ *
2037
+ * @version 5.2
2038
+ * @see https://www.mongodb.com/docs/manual/reference/operator/aggregation/bottom/#mongodb-group-grp.-bottom
2039
+ */
2040
+ $bottom: {
2041
+ sortBy: AnyObject,
2042
+ output: Expression
2043
+ };
2044
+ }
2045
+
2046
+ export interface BottomN {
2047
+ /**
2048
+ * Returns an aggregation of the bottom n elements within a group, according to the specified sort order.
2049
+ * If the group contains fewer than n elements, $bottomN returns all elements in the group.
2050
+ *
2051
+ * @version 5.2
2052
+ * @see https://www.mongodb.com/docs/manual/reference/operator/aggregation/bottomN/#mongodb-group-grp.-bottomN
2053
+ */
2054
+ $bottomN: {
2055
+ n: Expression,
2056
+ sortBy: AnyObject,
2057
+ output: Expression
2058
+ };
2059
+ }
2060
+
2003
2061
  export interface Count {
2004
2062
  /**
2005
2063
  * Returns the number of documents in a group.
@@ -2158,6 +2216,20 @@ declare module 'mongoose' {
2158
2216
  $max: Expression | Expression[];
2159
2217
  }
2160
2218
 
2219
+ export interface MaxN {
2220
+ /**
2221
+ * Returns an aggregation of the maxmimum value n elements within a group.
2222
+ * If the group contains fewer than n elements, $maxN returns all elements in the group.
2223
+ *
2224
+ * @version 5.2
2225
+ * @see https://www.mongodb.com/docs/manual/reference/operator/aggregation/maxN/#mongodb-group-grp.-maxN
2226
+ */
2227
+ $maxN: {
2228
+ input: Expression
2229
+ n: Expression,
2230
+ };
2231
+ }
2232
+
2161
2233
  export interface Min {
2162
2234
  /**
2163
2235
  * Returns the minimum value. $min compares both value and type, using the specified BSON comparison order for
@@ -2169,6 +2241,20 @@ declare module 'mongoose' {
2169
2241
  $min: Expression | Expression[];
2170
2242
  }
2171
2243
 
2244
+ export interface MinN {
2245
+ /**
2246
+ * Returns an aggregation of the minimum value n elements within a group.
2247
+ * If the group contains fewer than n elements, $minN returns all elements in the group.
2248
+ *
2249
+ * @version 5.2
2250
+ * @see https://www.mongodb.com/docs/manual/reference/operator/aggregation/minN/#mongodb-group-grp.-minN
2251
+ */
2252
+ $minN: {
2253
+ input: Expression
2254
+ n: Expression,
2255
+ };
2256
+ }
2257
+
2172
2258
  export interface Push {
2173
2259
  /**
2174
2260
  * Returns an array of all values that result from applying an expression to documents.
@@ -2605,6 +2691,8 @@ declare module 'mongoose' {
2605
2691
  export type ArrayExpressionOperatorReturningArray =
2606
2692
  Expression.ConcatArrays |
2607
2693
  Expression.Filter |
2694
+ Expression.FirstN |
2695
+ Expression.LastN |
2608
2696
  Expression.Map |
2609
2697
  Expression.ObjectToArray |
2610
2698
  Expression.Range |
@@ -2763,12 +2851,16 @@ declare module 'mongoose' {
2763
2851
  Expression.DocumentNumber |
2764
2852
  Expression.ExpMovingAvg |
2765
2853
  Expression.First |
2854
+ Expression.FirstN |
2766
2855
  Expression.Integral |
2767
2856
  Expression.Last |
2857
+ Expression.LastN |
2768
2858
  Expression.LinearFill |
2769
2859
  Expression.Locf |
2770
2860
  Expression.Max |
2861
+ Expression.MaxN |
2771
2862
  Expression.Min |
2863
+ Expression.MinN |
2772
2864
  Expression.Push |
2773
2865
  Expression.Rank |
2774
2866
  Expression.Shift |
@@ -2783,6 +2875,10 @@ declare module 'mongoose' {
2783
2875
 
2784
2876
  export type WindowOperatorReturningArray =
2785
2877
  Expression.AddToSet |
2878
+ Expression.FirstN |
2879
+ Expression.LastN |
2880
+ Expression.MaxN |
2881
+ Expression.MinN |
2786
2882
  Expression.Push;
2787
2883
 
2788
2884
  export type WindowOperatorReturningNumber =
@@ -2858,12 +2954,18 @@ declare module 'mongoose' {
2858
2954
  Expression.Accumulator |
2859
2955
  Expression.AddToSet |
2860
2956
  Expression.Avg |
2957
+ Expression.Bottom |
2958
+ Expression.BottomN |
2861
2959
  Expression.Count |
2862
2960
  Expression.First |
2961
+ Expression.FirstN |
2863
2962
  Expression.Last |
2963
+ Expression.LastN |
2864
2964
  Expression.Max |
2965
+ Expression.MaxN |
2865
2966
  Expression.MergeObjects |
2866
2967
  Expression.Min |
2968
+ Expression.MinN |
2867
2969
  Expression.Push |
2868
2970
  Expression.StdDevPop |
2869
2971
  Expression.StdDevSamp |
package/types/index.d.ts CHANGED
@@ -309,7 +309,7 @@ declare module 'mongoose' {
309
309
  eachPath(fn: (path: string, type: SchemaType) => void): this;
310
310
 
311
311
  /** Defines an index (most likely compound) for this schema. */
312
- index(fields: IndexDefinition, options?: IndexOptions): this;
312
+ index(fields: IndexDefinition, options?: Omit<IndexOptions, 'unique'> & { unique?: boolean | [true, string] }): this;
313
313
 
314
314
  /**
315
315
  * Define a search index for this schema.
@@ -63,7 +63,7 @@ declare module 'mongoose' {
63
63
  type ConnectionSyncIndexesResult = Record<string, OneCollectionSyncIndexesResult>;
64
64
  type OneCollectionSyncIndexesResult = Array<string> & mongodb.MongoServerError;
65
65
 
66
- interface IndexOptions extends mongodb.CreateIndexesOptions {
66
+ type IndexOptions = Omit<mongodb.CreateIndexesOptions, 'expires' | 'weights' | 'unique'> & {
67
67
  /**
68
68
  * `expires` utilizes the `ms` module from [guille](https://github.com/guille/) allowing us to use a friendlier syntax:
69
69
  *
@@ -86,7 +86,9 @@ declare module 'mongoose' {
86
86
  */
87
87
  expires?: number | string;
88
88
  weights?: Record<string, number>;
89
- }
89
+
90
+ unique?: boolean | [true, string]
91
+ };
90
92
 
91
93
  type SearchIndexDescription = mongodb.SearchIndexDescription;
92
94
  }