mongoose 7.3.3 → 7.4.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.
@@ -165,22 +165,22 @@ SubdocumentPath.prototype.cast = function(val, doc, init, priorVal, options) {
165
165
  let subdoc;
166
166
 
167
167
  // Only pull relevant selected paths and pull out the base path
168
- const parentSelected = doc && doc.$__ && doc.$__.selected || {};
168
+ const parentSelected = doc && doc.$__ && doc.$__.selected;
169
169
  const path = this.path;
170
- const selected = Object.keys(parentSelected).reduce((obj, key) => {
170
+ const selected = parentSelected == null ? null : Object.keys(parentSelected).reduce((obj, key) => {
171
171
  if (key.startsWith(path + '.')) {
172
172
  obj = obj || {};
173
173
  obj[key.substring(path.length + 1)] = parentSelected[key];
174
174
  }
175
175
  return obj;
176
176
  }, null);
177
- options = Object.assign({}, options, { priorDoc: priorVal });
178
177
  if (init) {
179
178
  subdoc = new Constructor(void 0, selected, doc, false, { defaults: false });
180
179
  delete subdoc.$__.defaults;
181
180
  subdoc.$init(val);
182
181
  applyDefaults(subdoc, selected);
183
182
  } else {
183
+ options = Object.assign({}, options, { priorDoc: priorVal });
184
184
  if (Object.keys(val).length === 0) {
185
185
  return new Constructor({}, selected, doc, undefined, options);
186
186
  }
@@ -212,11 +212,15 @@ SubdocumentPath.prototype.castForQuery = function($conditional, val, context, op
212
212
  return val;
213
213
  }
214
214
 
215
+ const Constructor = getConstructor(this.caster, val);
216
+ if (val instanceof Constructor) {
217
+ return val;
218
+ }
219
+
215
220
  if (this.options.runSetters) {
216
221
  val = this._applySetters(val, context);
217
222
  }
218
223
 
219
- const Constructor = getConstructor(this.caster, val);
220
224
  const overrideStrict = options != null && options.strict != null ?
221
225
  options.strict :
222
226
  void 0;
@@ -347,6 +351,8 @@ SubdocumentPath.defaultOptions = {};
347
351
 
348
352
  SubdocumentPath.set = SchemaType.set;
349
353
 
354
+ SubdocumentPath.setters = [];
355
+
350
356
  /**
351
357
  * Attaches a getter for all SubdocumentPath instances
352
358
  *
@@ -170,6 +170,8 @@ SchemaArray.defaultOptions = {};
170
170
  */
171
171
  SchemaArray.set = SchemaType.set;
172
172
 
173
+ SchemaArray.setters = [];
174
+
173
175
  /**
174
176
  * Attaches a getter for all Array instances
175
177
  *
@@ -62,6 +62,8 @@ SchemaBigInt._cast = castBigInt;
62
62
 
63
63
  SchemaBigInt.set = SchemaType.set;
64
64
 
65
+ SchemaBigInt.setters = [];
66
+
65
67
  /**
66
68
  * Attaches a getter for all BigInt instances
67
69
  *
@@ -65,6 +65,8 @@ SchemaBoolean._cast = castBoolean;
65
65
 
66
66
  SchemaBoolean.set = SchemaType.set;
67
67
 
68
+ SchemaBoolean.setters = [];
69
+
68
70
  /**
69
71
  * Attaches a getter for all Boolean instances
70
72
  *
@@ -70,6 +70,8 @@ SchemaBuffer._checkRequired = v => !!(v && v.length);
70
70
 
71
71
  SchemaBuffer.set = SchemaType.set;
72
72
 
73
+ SchemaBuffer.setters = [];
74
+
73
75
  /**
74
76
  * Attaches a getter for all Buffer instances
75
77
  *
@@ -70,6 +70,8 @@ SchemaDate._cast = castDate;
70
70
 
71
71
  SchemaDate.set = SchemaType.set;
72
72
 
73
+ SchemaDate.setters = [];
74
+
73
75
  /**
74
76
  * Attaches a getter for all Date instances
75
77
  *
@@ -66,6 +66,8 @@ Decimal128._cast = castDecimal128;
66
66
 
67
67
  Decimal128.set = SchemaType.set;
68
68
 
69
+ Decimal128.setters = [];
70
+
69
71
  /**
70
72
  * Attaches a getter for all Decimal128 instances
71
73
  *
@@ -605,6 +605,8 @@ DocumentArrayPath.defaultOptions = {};
605
605
 
606
606
  DocumentArrayPath.set = SchemaType.set;
607
607
 
608
+ DocumentArrayPath.setters = [];
609
+
608
610
  /**
609
611
  * Attaches a getter for all DocumentArrayPath instances
610
612
  *
@@ -94,6 +94,8 @@ Mixed.get = SchemaType.get;
94
94
 
95
95
  Mixed.set = SchemaType.set;
96
96
 
97
+ Mixed.setters = [];
98
+
97
99
  /**
98
100
  * Casts `val` for Mixed.
99
101
  *
@@ -67,6 +67,8 @@ SchemaNumber.get = SchemaType.get;
67
67
 
68
68
  SchemaNumber.set = SchemaType.set;
69
69
 
70
+ SchemaNumber.setters = [];
71
+
70
72
  /*!
71
73
  * ignore
72
74
  */
@@ -94,6 +94,8 @@ ObjectId.get = SchemaType.get;
94
94
 
95
95
  ObjectId.set = SchemaType.set;
96
96
 
97
+ ObjectId.setters = [];
98
+
97
99
  /**
98
100
  * Adds an auto-generated ObjectId default if turnOn is true.
99
101
  * @param {Boolean} turnOn auto generated ObjectId defaults
@@ -143,6 +143,8 @@ SchemaString.get = SchemaType.get;
143
143
 
144
144
  SchemaString.set = SchemaType.set;
145
145
 
146
+ SchemaString.setters = [];
147
+
146
148
  /*!
147
149
  * ignore
148
150
  */
@@ -194,6 +194,8 @@ SchemaUUID.get = SchemaType.get;
194
194
 
195
195
  SchemaUUID.set = SchemaType.set;
196
196
 
197
+ SchemaUUID.setters = [];
198
+
197
199
  /**
198
200
  * Get/set the function used to cast arbitrary values to UUIDs.
199
201
  *
package/lib/schema.js CHANGED
@@ -80,6 +80,7 @@ let id = 0;
80
80
  * - [timestamps](https://mongoosejs.com/docs/guide.html#timestamps): object or boolean - defaults to `false`. If true, Mongoose adds `createdAt` and `updatedAt` properties to your schema and manages those properties for you.
81
81
  * - [pluginTags](https://mongoosejs.com/docs/guide.html#pluginTags): array of strings - defaults to `undefined`. If set and plugin called with `tags` option, will only apply that plugin to schemas with a matching tag.
82
82
  * - [virtuals](https://mongoosejs.com/docs/tutorials/virtuals.html#virtuals-via-schema-options): object - virtuals to define, alias for [`.virtual`](https://mongoosejs.com/docs/api/schema.html#Schema.prototype.virtual())
83
+ * - [collectionOptions]: object with options passed to [`createCollection()`](https://www.mongodb.com/docs/manual/reference/method/db.createCollection/) when calling `Model.createCollection()` or `autoCreate` set to true.
83
84
  *
84
85
  * #### Options for Nested Schemas:
85
86
  *
@@ -1585,9 +1586,6 @@ Schema.prototype.indexedPaths = function indexedPaths() {
1585
1586
  */
1586
1587
 
1587
1588
  Schema.prototype.pathType = function(path) {
1588
- // Convert to '.$' to check subpaths re: gh-6405
1589
- const cleanPath = _pathToPositionalSyntax(path);
1590
-
1591
1589
  if (this.paths.hasOwnProperty(path)) {
1592
1590
  return 'real';
1593
1591
  }
@@ -1597,6 +1595,10 @@ Schema.prototype.pathType = function(path) {
1597
1595
  if (this.nested.hasOwnProperty(path)) {
1598
1596
  return 'nested';
1599
1597
  }
1598
+
1599
+ // Convert to '.$' to check subpaths re: gh-6405
1600
+ const cleanPath = _pathToPositionalSyntax(path);
1601
+
1600
1602
  if (this.subpaths.hasOwnProperty(cleanPath) || this.subpaths.hasOwnProperty(path)) {
1601
1603
  return 'real';
1602
1604
  }
package/lib/schematype.js CHANGED
@@ -48,7 +48,9 @@ function SchemaType(path, options, instance) {
48
48
  this.getters = this.constructor.hasOwnProperty('getters') ?
49
49
  this.constructor.getters.slice() :
50
50
  [];
51
- this.setters = [];
51
+ this.setters = this.constructor.hasOwnProperty('setters') ?
52
+ this.constructor.setters.slice() :
53
+ [];
52
54
 
53
55
  this.splitPath();
54
56
 
@@ -80,7 +82,11 @@ function SchemaType(path, options, instance) {
80
82
  const keys = Object.keys(this.options);
81
83
  for (const prop of keys) {
82
84
  if (prop === 'cast') {
83
- this.castFunction(this.options[prop]);
85
+ if (Array.isArray(this.options[prop])) {
86
+ this.castFunction.apply(this, this.options[prop]);
87
+ } else {
88
+ this.castFunction(this.options[prop]);
89
+ }
84
90
  continue;
85
91
  }
86
92
  if (utils.hasUserDefinedProperty(this.options, prop) && typeof this[prop] === 'function') {
@@ -253,14 +259,24 @@ SchemaType.cast = function cast(caster) {
253
259
  * @api public
254
260
  */
255
261
 
256
- SchemaType.prototype.castFunction = function castFunction(caster) {
262
+ SchemaType.prototype.castFunction = function castFunction(caster, message) {
257
263
  if (arguments.length === 0) {
258
264
  return this._castFunction;
259
265
  }
266
+
260
267
  if (caster === false) {
261
268
  caster = this.constructor._defaultCaster || (v => v);
262
269
  }
263
- this._castFunction = caster;
270
+ if (typeof caster === 'string') {
271
+ this._castErrorMessage = caster;
272
+ return this._castFunction;
273
+ }
274
+ if (caster != null) {
275
+ this._castFunction = caster;
276
+ }
277
+ if (message != null) {
278
+ this._castErrorMessage = message;
279
+ }
264
280
 
265
281
  return this._castFunction;
266
282
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mongoose",
3
3
  "description": "Mongoose MongoDB ODM",
4
- "version": "7.3.3",
4
+ "version": "7.4.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": "^5.3.0",
22
+ "bson": "^5.4.0",
23
23
  "kareem": "2.5.1",
24
- "mongodb": "5.6.0",
24
+ "mongodb": "5.7.0",
25
25
  "mpath": "0.9.0",
26
26
  "mquery": "5.0.0",
27
27
  "ms": "2.1.3",
@@ -0,0 +1,9 @@
1
+ // this import is required so that types get merged instead of completely overwritten
2
+ import 'bson';
3
+
4
+ declare module 'bson' {
5
+ interface ObjectId {
6
+ /** Mongoose automatically adds a conveniency "_id" getter on the base ObjectId class */
7
+ _id: this;
8
+ }
9
+ }
package/types/index.d.ts CHANGED
@@ -22,6 +22,7 @@
22
22
  /// <reference path="./validation.d.ts" />
23
23
  /// <reference path="./inferschematype.d.ts" />
24
24
  /// <reference path="./virtuals.d.ts" />
25
+ /// <reference path="./augmentations.d.ts" />
25
26
 
26
27
  declare class NativeDate extends global.Date { }
27
28
 
package/types/models.d.ts CHANGED
@@ -123,7 +123,6 @@ declare module 'mongoose' {
123
123
  SessionOption {
124
124
  checkKeys?: boolean;
125
125
  j?: boolean;
126
- ordered?: boolean;
127
126
  safe?: boolean | WriteConcern;
128
127
  timestamps?: boolean | QueryTimestampsConfig;
129
128
  validateBeforeSave?: boolean;
@@ -132,6 +131,11 @@ declare module 'mongoose' {
132
131
  wtimeout?: number;
133
132
  }
134
133
 
134
+ interface CreateOptions extends SaveOptions {
135
+ ordered?: boolean;
136
+ aggregateErrors?: boolean;
137
+ }
138
+
135
139
  interface RemoveOptions extends SessionOption, Omit<mongodb.DeleteOptions, 'session'> {}
136
140
 
137
141
  const Model: Model<any>;
@@ -217,7 +221,8 @@ declare module 'mongoose' {
217
221
  >;
218
222
 
219
223
  /** Creates a new document or documents */
220
- create<DocContents = AnyKeys<TRawDocType>>(docs: Array<TRawDocType | DocContents>, options?: SaveOptions): Promise<THydratedDocumentType[]>;
224
+ create<DocContents = AnyKeys<TRawDocType>>(docs: Array<TRawDocType | DocContents>, options: CreateOptions & { aggregateErrors: true }): Promise<(THydratedDocumentType | Error)[]>;
225
+ create<DocContents = AnyKeys<TRawDocType>>(docs: Array<TRawDocType | DocContents>, options?: CreateOptions): Promise<THydratedDocumentType[]>;
221
226
  create<DocContents = AnyKeys<TRawDocType>>(doc: DocContents | TRawDocType): Promise<THydratedDocumentType>;
222
227
  create<DocContents = AnyKeys<TRawDocType>>(...docs: Array<TRawDocType | DocContents>): Promise<THydratedDocumentType[]>;
223
228
 
package/types/query.d.ts CHANGED
@@ -691,7 +691,7 @@ declare module 'mongoose' {
691
691
  slice(val: number | Array<number>): this;
692
692
 
693
693
  /** Sets the sort order. If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. */
694
- sort(arg?: string | { [key: string]: SortOrder | { $meta: 'textScore' } } | [string, SortOrder][] | undefined | null): this;
694
+ sort(arg?: string | { [key: string]: SortOrder | { $meta: any } } | [string, SortOrder][] | undefined | null): this;
695
695
 
696
696
  /** Sets the tailable option (for use with capped collections). */
697
697
  tailable(bool?: boolean, opts?: {
@@ -49,6 +49,9 @@ declare module 'mongoose' {
49
49
  /** Sets a default collation for every query and aggregation. */
50
50
  collation?: mongodb.CollationOptions;
51
51
 
52
+ /** Arbitrary options passed to `createCollection()` */
53
+ collectionOptions?: mongodb.CreateCollectionOptions;
54
+
52
55
  /** The timeseries option to use when creating the model's collection. */
53
56
  timeseries?: mongodb.TimeSeriesCollectionOptions;
54
57
 
@@ -63,7 +63,11 @@ declare module 'mongoose' {
63
63
  validate?: SchemaValidator<T> | AnyArray<SchemaValidator<T>>;
64
64
 
65
65
  /** Allows overriding casting logic for this individual path. If a string, the given string overwrites Mongoose's default cast error message. */
66
- cast?: string;
66
+ cast?: string |
67
+ boolean |
68
+ ((value: any) => T) |
69
+ [(value: any) => T, string] |
70
+ [((value: any) => T) | null, (value: any, path: string, model: Model<any>, kind: string) => string];
67
71
 
68
72
  /**
69
73
  * If true, attach a required validator to this path, which ensures this path
package/types/types.d.ts CHANGED
@@ -80,7 +80,6 @@ declare module 'mongoose' {
80
80
  }
81
81
 
82
82
  class ObjectId extends mongodb.ObjectId {
83
- _id: this;
84
83
  }
85
84
 
86
85
  class Subdocument<IdType = any> extends Document<IdType> {
@@ -1,39 +0,0 @@
1
- 'use strict';
2
-
3
- const MongooseError = require('../../error/mongooseError');
4
- const isMongooseObject = require('../isMongooseObject');
5
- const setDottedPath = require('../path/setDottedPath');
6
- const util = require('util');
7
-
8
- /**
9
- * Given an object that may contain dotted paths, flatten the paths out.
10
- * For example: `flattenObjectWithDottedPaths({ a: { 'b.c': 42 } })` => `{ a: { b: { c: 42 } } }`
11
- */
12
-
13
- module.exports = function flattenObjectWithDottedPaths(obj) {
14
- if (obj == null || typeof obj !== 'object' || Array.isArray(obj)) {
15
- return;
16
- }
17
- // Avoid Mongoose docs, like docs and maps, because these may cause infinite recursion
18
- if (isMongooseObject(obj)) {
19
- return;
20
- }
21
- const keys = Object.keys(obj);
22
- for (const key of keys) {
23
- const val = obj[key];
24
- if (key.indexOf('.') !== -1) {
25
- try {
26
- delete obj[key];
27
- setDottedPath(obj, key, val);
28
- } catch (err) {
29
- if (!(err instanceof TypeError)) {
30
- throw err;
31
- }
32
- throw new MongooseError(`Conflicting dotted paths when setting document path, key: "${key}", value: ${util.inspect(val)}`);
33
- }
34
- continue;
35
- }
36
-
37
- flattenObjectWithDottedPaths(obj[key]);
38
- }
39
- };