mongoose 8.7.1 → 8.7.3

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.
@@ -196,6 +196,37 @@ AggregationCursor.prototype.close = async function close() {
196
196
  this.emit('close');
197
197
  };
198
198
 
199
+ /**
200
+ * Marks this cursor as destroyed. Will stop streaming and subsequent calls to
201
+ * `next()` will error.
202
+ *
203
+ * @return {this}
204
+ * @api private
205
+ * @method _destroy
206
+ */
207
+
208
+ AggregationCursor.prototype._destroy = function _destroy(_err, callback) {
209
+ let waitForCursor = null;
210
+ if (!this.cursor) {
211
+ waitForCursor = new Promise((resolve) => {
212
+ this.once('cursor', resolve);
213
+ });
214
+ } else {
215
+ waitForCursor = Promise.resolve();
216
+ }
217
+
218
+ waitForCursor
219
+ .then(() => this.cursor.close())
220
+ .then(() => {
221
+ this._closed = true;
222
+ callback();
223
+ })
224
+ .catch(error => {
225
+ callback(error);
226
+ });
227
+ return this;
228
+ };
229
+
199
230
  /**
200
231
  * Get the next document from this cursor. Will return `null` when there are
201
232
  * no documents left.
@@ -238,6 +238,39 @@ QueryCursor.prototype.close = async function close() {
238
238
  }
239
239
  };
240
240
 
241
+ /**
242
+ * Marks this cursor as destroyed. Will stop streaming and subsequent calls to
243
+ * `next()` will error.
244
+ *
245
+ * @return {this}
246
+ * @api private
247
+ * @method _destroy
248
+ */
249
+
250
+ QueryCursor.prototype._destroy = function _destroy(_err, callback) {
251
+ let waitForCursor = null;
252
+ if (!this.cursor) {
253
+ waitForCursor = new Promise((resolve) => {
254
+ this.once('cursor', resolve);
255
+ });
256
+ } else {
257
+ waitForCursor = Promise.resolve();
258
+ }
259
+
260
+ waitForCursor
261
+ .then(() => {
262
+ this.cursor.close();
263
+ })
264
+ .then(() => {
265
+ this._closed = true;
266
+ callback();
267
+ })
268
+ .catch(error => {
269
+ callback(error);
270
+ });
271
+ return this;
272
+ };
273
+
241
274
  /**
242
275
  * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will
243
276
  * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even
@@ -25,11 +25,21 @@ module.exports = function cleanModifiedSubpaths(doc, path, options) {
25
25
  ++deleted;
26
26
 
27
27
  if (doc.$isSubdocument) {
28
- const owner = doc.ownerDocument();
29
- const fullPath = doc.$__fullPath(modifiedPath);
30
- owner.$__.activePaths.clearPath(fullPath);
28
+ cleanParent(doc, modifiedPath);
31
29
  }
32
30
  }
33
31
  }
34
32
  return deleted;
35
33
  };
34
+
35
+ function cleanParent(doc, path, seen = new Set()) {
36
+ if (seen.has(doc)) {
37
+ throw new Error('Infinite subdocument loop: subdoc with _id ' + doc._id + ' is a parent of itself');
38
+ }
39
+ const parent = doc.$parent();
40
+ const newPath = doc.$__pathRelativeToParent(void 0, false) + '.' + path;
41
+ parent.$__.activePaths.clearPath(newPath);
42
+ if (parent.$isSubdocument) {
43
+ cleanParent(parent, newPath, seen);
44
+ }
45
+ }
@@ -478,9 +478,10 @@ function addModelNamesToMap(model, map, available, modelNames, options, data, re
478
478
  return;
479
479
  }
480
480
 
481
- let k = modelNames.length;
481
+ const flatModelNames = utils.array.flatten(modelNames);
482
+ let k = flatModelNames.length;
482
483
  while (k--) {
483
- let modelName = modelNames[k];
484
+ let modelName = flatModelNames[k];
484
485
  if (modelName == null) {
485
486
  continue;
486
487
  }
@@ -503,11 +504,10 @@ function addModelNamesToMap(model, map, available, modelNames, options, data, re
503
504
  }
504
505
 
505
506
  let ids = ret;
506
- const flat = Array.isArray(ret) ? utils.array.flatten(ret) : [];
507
507
 
508
508
  const modelNamesForRefPath = data.modelNamesInOrder ? data.modelNamesInOrder : modelNames;
509
- if (data.isRefPath && Array.isArray(ret) && flat.length === modelNamesForRefPath.length) {
510
- ids = flat.filter((val, i) => modelNamesForRefPath[i] === modelName);
509
+ if (data.isRefPath && Array.isArray(ret) && ret.length === modelNamesForRefPath.length) {
510
+ ids = matchIdsToRefPaths(ret, modelNamesForRefPath, modelName);
511
511
  }
512
512
 
513
513
  const perDocumentLimit = options.perDocumentLimit == null ?
@@ -569,6 +569,20 @@ function _getModelFromConn(conn, modelName) {
569
569
  return conn.model(modelName);
570
570
  }
571
571
 
572
+ function matchIdsToRefPaths(ids, refPaths, refPathToFind) {
573
+ if (!Array.isArray(refPaths)) {
574
+ return refPaths === refPathToFind
575
+ ? Array.isArray(ids)
576
+ ? utils.array.flatten(ids)
577
+ : [ids]
578
+ : [];
579
+ }
580
+ if (Array.isArray(ids) && Array.isArray(refPaths)) {
581
+ return ids.flatMap((id, index) => matchIdsToRefPaths(id, refPaths[index], refPathToFind));
582
+ }
583
+ return [];
584
+ }
585
+
572
586
  /*!
573
587
  * ignore
574
588
  */
@@ -62,7 +62,5 @@ module.exports = function modelNamesFromRefPath(refPath, doc, populatedPath, mod
62
62
  modelNames = Array.isArray(refValue) ? refValue : [refValue];
63
63
  }
64
64
 
65
- modelNames = utils.array.flatten(modelNames);
66
-
67
65
  return modelNames;
68
66
  };
package/lib/model.js CHANGED
@@ -3771,7 +3771,7 @@ Model.hydrate = function(obj, projection, options) {
3771
3771
  * const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true });
3772
3772
  * res.matchedCount; // Number of documents matched
3773
3773
  * res.modifiedCount; // Number of documents modified
3774
- * res.acknowledged; // Boolean indicating everything went smoothly.
3774
+ * res.acknowledged; // Boolean indicating the MongoDB server received the operation. This may be false if Mongoose did not send an update to the server because the update was empty.
3775
3775
  * res.upsertedId; // null or an id containing a document that had to be upserted.
3776
3776
  * res.upsertedCount; // Number indicating how many documents had to be upserted. Will either be 0 or 1.
3777
3777
  *
@@ -3811,7 +3811,7 @@ Model.updateMany = function updateMany(conditions, doc, options) {
3811
3811
  * const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' });
3812
3812
  * res.matchedCount; // Number of documents matched
3813
3813
  * res.modifiedCount; // Number of documents modified
3814
- * res.acknowledged; // Boolean indicating everything went smoothly.
3814
+ * res.acknowledged; // Boolean indicating the MongoDB server received the operation. This may be false if Mongoose did not send an update to the server because the update was empty.
3815
3815
  * res.upsertedId; // null or an id containing a document that had to be upserted.
3816
3816
  * res.upsertedCount; // Number indicating how many documents had to be upserted. Will either be 0 or 1.
3817
3817
  *
@@ -3849,7 +3849,7 @@ Model.updateOne = function updateOne(conditions, doc, options) {
3849
3849
  * const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' });
3850
3850
  * res.matchedCount; // Number of documents matched
3851
3851
  * res.modifiedCount; // Number of documents modified
3852
- * res.acknowledged; // Boolean indicating everything went smoothly.
3852
+ * res.acknowledged; // Boolean indicating the MongoDB server received the operation.
3853
3853
  * res.upsertedId; // null or an id containing a document that had to be upserted.
3854
3854
  * res.upsertedCount; // Number indicating how many documents had to be upserted. Will either be 0 or 1.
3855
3855
  *
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mongoose",
3
3
  "description": "Mongoose MongoDB ODM",
4
- "version": "8.7.1",
4
+ "version": "8.7.3",
5
5
  "author": "Guillermo Rauch <guillermo@learnboost.com>",
6
6
  "keywords": [
7
7
  "mongodb",
@@ -92,7 +92,7 @@
92
92
  "lint": "eslint .",
93
93
  "lint-js": "eslint . --ext .js --ext .cjs",
94
94
  "lint-ts": "eslint . --ext .ts",
95
- "lint-md": "markdownlint-cli2 \"**/*.md\"",
95
+ "lint-md": "markdownlint-cli2 \"**/*.md\" \"#node_modules\" \"#benchmarks\"",
96
96
  "build-browser": "(rm ./dist/* || true) && node ./scripts/build-browser.js",
97
97
  "prepublishOnly": "npm run build-browser",
98
98
  "release": "git pull && git push origin master --tags && npm publish",
@@ -50,6 +50,12 @@ declare module 'mongoose' {
50
50
  autoIndex?: boolean;
51
51
  /** Set to `false` to disable Mongoose automatically calling `createCollection()` on every model created on this connection. */
52
52
  autoCreate?: boolean;
53
+ /**
54
+ * Sanitizes query filters against [query selector injection attacks](
55
+ * https://thecodebarbarian.com/2014/09/04/defending-against-query-selector-injection-attacks.html
56
+ * ) by wrapping any nested objects that have a property whose name starts with $ in a $eq.
57
+ */
58
+ sanitizeFilter?: boolean;
53
59
  }
54
60
 
55
61
  class Connection extends events.EventEmitter implements SessionStarter {
package/types/cursor.d.ts CHANGED
@@ -26,6 +26,12 @@ declare module 'mongoose' {
26
26
  */
27
27
  close(): Promise<void>;
28
28
 
29
+ /**
30
+ * Destroy this cursor, closing the underlying cursor. Will stop streaming
31
+ * and subsequent calls to `next()` will error.
32
+ */
33
+ destroy(): this;
34
+
29
35
  /**
30
36
  * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will
31
37
  * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even
package/types/index.d.ts CHANGED
@@ -706,6 +706,91 @@ declare module 'mongoose' {
706
706
  [K in keyof T]: FlattenProperty<T[K]>;
707
707
  };
708
708
 
709
+ /**
710
+ * Converts any Buffer properties into mongodb.Binary instances, which is what `lean()` returns
711
+ */
712
+ export type BufferToBinary<T> = T extends TreatAsPrimitives ? T : T extends Record<string, any> ? {
713
+ [K in keyof T]: T[K] extends Buffer
714
+ ? mongodb.Binary
715
+ : T[K] extends (Buffer | null | undefined)
716
+ ? mongodb.Binary | null | undefined
717
+ : T[K] extends Types.DocumentArray<infer ItemType>
718
+ ? Types.DocumentArray<BufferToBinary<ItemType>>
719
+ : T[K] extends Types.Subdocument<unknown, unknown, infer SubdocType>
720
+ ? HydratedSingleSubdocument<SubdocType>
721
+ : BufferToBinary<T[K]>;
722
+ } : T;
723
+
724
+ /**
725
+ * Converts any Buffer properties into { type: 'buffer', data: [1, 2, 3] } format for JSON serialization
726
+ */
727
+ export type BufferToJSON<T> = T extends TreatAsPrimitives ? T : T extends Record<string, any> ? {
728
+ [K in keyof T]: T[K] extends Buffer
729
+ ? { type: 'buffer', data: number[] }
730
+ : T[K] extends (Buffer | null | undefined)
731
+ ? { type: 'buffer', data: number[] } | null | undefined
732
+ : T[K] extends Types.DocumentArray<infer ItemType>
733
+ ? Types.DocumentArray<BufferToBinary<ItemType>>
734
+ : T[K] extends Types.Subdocument<unknown, unknown, infer SubdocType>
735
+ ? HydratedSingleSubdocument<SubdocType>
736
+ : BufferToBinary<T[K]>;
737
+ } : T;
738
+
739
+ /**
740
+ * Converts any ObjectId properties into strings for JSON serialization
741
+ */
742
+ export type ObjectIdToString<T> = T extends TreatAsPrimitives ? T : T extends Record<string, any> ? {
743
+ [K in keyof T]: T[K] extends mongodb.ObjectId
744
+ ? string
745
+ : T[K] extends (mongodb.ObjectId | null | undefined)
746
+ ? string | null | undefined
747
+ : T[K] extends Types.DocumentArray<infer ItemType>
748
+ ? Types.DocumentArray<ObjectIdToString<ItemType>>
749
+ : T[K] extends Types.Subdocument<unknown, unknown, infer SubdocType>
750
+ ? HydratedSingleSubdocument<ObjectIdToString<SubdocType>>
751
+ : ObjectIdToString<T[K]>;
752
+ } : T;
753
+
754
+ /**
755
+ * Converts any Date properties into strings for JSON serialization
756
+ */
757
+ export type DateToString<T> = T extends TreatAsPrimitives ? T : T extends Record<string, any> ? {
758
+ [K in keyof T]: T[K] extends NativeDate
759
+ ? string
760
+ : T[K] extends (NativeDate | null | undefined)
761
+ ? string | null | undefined
762
+ : T[K] extends Types.DocumentArray<infer ItemType>
763
+ ? Types.DocumentArray<DateToString<ItemType>>
764
+ : T[K] extends Types.Subdocument<unknown, unknown, infer SubdocType>
765
+ ? HydratedSingleSubdocument<DateToString<SubdocType>>
766
+ : DateToString<T[K]>;
767
+ } : T;
768
+
769
+ /**
770
+ * Converts any Mongoose subdocuments (single nested or doc arrays) into POJO equivalents
771
+ */
772
+ export type SubdocsToPOJOs<T> = T extends TreatAsPrimitives ? T : T extends Record<string, any> ? {
773
+ [K in keyof T]: T[K] extends NativeDate
774
+ ? string
775
+ : T[K] extends (NativeDate | null | undefined)
776
+ ? string | null | undefined
777
+ : T[K] extends Types.DocumentArray<infer ItemType>
778
+ ? ItemType[]
779
+ : T[K] extends Types.Subdocument<unknown, unknown, infer SubdocType>
780
+ ? SubdocType
781
+ : SubdocsToPOJOs<T[K]>;
782
+ } : T;
783
+
784
+ export type JSONSerialized<T> = SubdocsToPOJOs<
785
+ FlattenMaps<
786
+ BufferToJSON<
787
+ ObjectIdToString<
788
+ DateToString<T>
789
+ >
790
+ >
791
+ >
792
+ >;
793
+
709
794
  /**
710
795
  * Separate type is needed for properties of union type (for example, Types.DocumentArray | undefined) to apply conditional check to each member of it
711
796
  * https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types
@@ -716,7 +801,7 @@ declare module 'mongoose' {
716
801
  ? Types.DocumentArray<FlattenMaps<ItemType>> : FlattenMaps<T>;
717
802
 
718
803
  export type actualPrimitives = string | boolean | number | bigint | symbol | null | undefined;
719
- export type TreatAsPrimitives = actualPrimitives | NativeDate | RegExp | symbol | Error | BigInt | Types.ObjectId | Buffer | Function;
804
+ export type TreatAsPrimitives = actualPrimitives | NativeDate | RegExp | symbol | Error | BigInt | Types.ObjectId | Buffer | Function | mongodb.Binary;
720
805
 
721
806
  export type SchemaDefinitionType<T> = T extends Document ? Omit<T, Exclude<keyof Document, '_id' | 'id' | '__v'>> : T;
722
807
 
@@ -146,9 +146,10 @@ type RequiredPathKeys<T, TypeKey extends string = DefaultTypeKey> = {
146
146
  * @param {TypeKey} TypeKey A generic of literal string type."Refers to the property used for path type definition".
147
147
  * @returns a record contains required paths with the corresponding type.
148
148
  */
149
- type RequiredPaths<T, TypeKey extends string = DefaultTypeKey> = {
150
- [K in RequiredPathKeys<T, TypeKey>]: T[K];
151
- };
149
+ type RequiredPaths<T, TypeKey extends string = DefaultTypeKey> = Pick<
150
+ { -readonly [K in keyof T]: T[K] },
151
+ RequiredPathKeys<T, TypeKey>
152
+ >;
152
153
 
153
154
  /**
154
155
  * @summary A Utility to obtain schema's optional path keys.
@@ -166,9 +167,10 @@ type OptionalPathKeys<T, TypeKey extends string = DefaultTypeKey> = {
166
167
  * @param {TypeKey} TypeKey A generic of literal string type."Refers to the property used for path type definition".
167
168
  * @returns a record contains optional paths with the corresponding type.
168
169
  */
169
- type OptionalPaths<T, TypeKey extends string = DefaultTypeKey> = {
170
- [K in OptionalPathKeys<T, TypeKey>]?: T[K];
171
- };
170
+ type OptionalPaths<T, TypeKey extends string = DefaultTypeKey> = Pick<
171
+ { -readonly [K in keyof T]?: T[K] },
172
+ OptionalPathKeys<T, TypeKey>
173
+ >;
172
174
 
173
175
  /**
174
176
  * @summary Allows users to optionally choose their own type for a schema field for stronger typing.
@@ -183,8 +185,16 @@ type TypeHint<T> = T extends { __typehint: infer U } ? U: never;
183
185
  * @param {TypeKey} TypeKey A generic refers to document definition.
184
186
  */
185
187
  type ObtainDocumentPathType<PathValueType, TypeKey extends string = DefaultTypeKey> = ResolvePathType<
186
- PathValueType extends PathWithTypePropertyBaseType<TypeKey> ? PathValueType[TypeKey] : PathValueType,
187
- PathValueType extends PathWithTypePropertyBaseType<TypeKey> ? Omit<PathValueType, TypeKey> : {},
188
+ PathValueType extends PathWithTypePropertyBaseType<TypeKey>
189
+ ? PathValueType[TypeKey] extends PathWithTypePropertyBaseType<TypeKey>
190
+ ? PathValueType
191
+ : PathValueType[TypeKey]
192
+ : PathValueType,
193
+ PathValueType extends PathWithTypePropertyBaseType<TypeKey>
194
+ ? PathValueType[TypeKey] extends PathWithTypePropertyBaseType<TypeKey>
195
+ ? {}
196
+ : Omit<PathValueType, TypeKey>
197
+ : {},
188
198
  TypeKey,
189
199
  TypeHint<PathValueType>
190
200
  >;
package/types/models.d.ts CHANGED
@@ -64,14 +64,13 @@ declare module 'mongoose' {
64
64
  throwOnValidationError?: boolean;
65
65
  }
66
66
 
67
- type InsertManyResult<T> = mongodb.InsertManyResult<T> & {
68
- insertedIds: {
69
- [key: number]: InferId<T>;
70
- };
67
+ interface InsertManyResult<T> extends mongodb.InsertManyResult<T> {
71
68
  mongoose?: { validationErrors?: Array<Error.CastError | Error.ValidatorError> };
72
- };
69
+ }
73
70
 
74
71
  type UpdateWriteOpResult = mongodb.UpdateResult;
72
+ type UpdateResult = mongodb.UpdateResult;
73
+ type DeleteResult = mongodb.DeleteResult;
75
74
 
76
75
  interface MapReduceOptions<T, K, R> {
77
76
  map: Function | string;
package/types/query.d.ts CHANGED
@@ -211,7 +211,7 @@ declare module 'mongoose' {
211
211
  type QueryOpThatReturnsDocument = 'find' | 'findOne' | 'findOneAndUpdate' | 'findOneAndReplace' | 'findOneAndDelete';
212
212
 
213
213
  type GetLeanResultType<RawDocType, ResultType, QueryOp> = QueryOp extends QueryOpThatReturnsDocument
214
- ? (ResultType extends any[] ? Require_id<FlattenMaps<RawDocType>>[] : Require_id<FlattenMaps<RawDocType>>)
214
+ ? (ResultType extends any[] ? Require_id<BufferToBinary<FlattenMaps<RawDocType>>>[] : Require_id<BufferToBinary<FlattenMaps<RawDocType>>>)
215
215
  : ResultType;
216
216
 
217
217
  type MergePopulatePaths<RawDocType, ResultType, QueryOp, Paths, TQueryHelpers, TInstanceMethods = Record<string, never>> = QueryOp extends QueryOpThatReturnsDocument