@kikiutils/mongoose 9.0.5 → 10.0.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.
Files changed (211) hide show
  1. package/README.md +13 -25
  2. package/dist/_internals.d.ts +10 -1
  3. package/dist/_internals.d.ts.map +1 -1
  4. package/dist/_internals.js +20 -1
  5. package/dist/_internals.js.map +1 -1
  6. package/dist/assertions.d.ts +5 -2
  7. package/dist/assertions.d.ts.map +1 -1
  8. package/dist/assertions.js +10 -4
  9. package/dist/assertions.js.map +1 -1
  10. package/dist/builders.d.ts +9 -4
  11. package/dist/builders.d.ts.map +1 -1
  12. package/dist/builders.js +9 -9
  13. package/dist/builders.js.map +1 -1
  14. package/dist/connection.d.ts +3 -0
  15. package/dist/connection.d.ts.map +1 -1
  16. package/dist/connection.js +7 -1
  17. package/dist/connection.js.map +1 -1
  18. package/dist/documents.d.ts +8 -0
  19. package/dist/documents.d.ts.map +1 -0
  20. package/dist/documents.js +10 -0
  21. package/dist/documents.js.map +1 -0
  22. package/dist/errors/duplicate-key.d.ts +9 -0
  23. package/dist/errors/duplicate-key.d.ts.map +1 -0
  24. package/dist/errors/duplicate-key.js +15 -0
  25. package/dist/errors/duplicate-key.js.map +1 -0
  26. package/dist/errors/mongoose-update-conflict-error.d.ts +4 -0
  27. package/dist/errors/mongoose-update-conflict-error.d.ts.map +1 -0
  28. package/dist/errors/mongoose-update-conflict-error.js +7 -0
  29. package/dist/errors/mongoose-update-conflict-error.js.map +1 -0
  30. package/dist/options.d.ts +15 -1
  31. package/dist/options.d.ts.map +1 -1
  32. package/dist/options.js +19 -2
  33. package/dist/options.js.map +1 -1
  34. package/dist/plugins/assertions.d.ts +30 -9
  35. package/dist/plugins/assertions.d.ts.map +1 -1
  36. package/dist/plugins/assertions.js +32 -4
  37. package/dist/plugins/assertions.js.map +1 -1
  38. package/dist/plugins/lean-decimal128-to-string.d.ts +3 -15
  39. package/dist/plugins/lean-decimal128-to-string.d.ts.map +1 -1
  40. package/dist/plugins/lean-decimal128-to-string.js +30 -23
  41. package/dist/plugins/lean-decimal128-to-string.js.map +1 -1
  42. package/dist/plugins/normalize.d.ts +3 -40
  43. package/dist/plugins/normalize.d.ts.map +1 -1
  44. package/dist/plugins/normalize.js +98 -44
  45. package/dist/plugins/normalize.js.map +1 -1
  46. package/dist/schema-builders/_internals/array.d.ts +9 -0
  47. package/dist/schema-builders/_internals/array.d.ts.map +1 -0
  48. package/dist/schema-builders/_internals/array.js +12 -0
  49. package/dist/schema-builders/_internals/array.js.map +1 -0
  50. package/dist/schema-builders/_internals/boolean.d.ts +8 -0
  51. package/dist/schema-builders/_internals/boolean.d.ts.map +1 -0
  52. package/dist/schema-builders/_internals/boolean.js +9 -0
  53. package/dist/schema-builders/_internals/boolean.js.map +1 -0
  54. package/dist/schema-builders/_internals/date.d.ts +8 -0
  55. package/dist/schema-builders/_internals/date.d.ts.map +1 -0
  56. package/dist/schema-builders/_internals/date.js +9 -0
  57. package/dist/schema-builders/_internals/date.js.map +1 -0
  58. package/dist/schema-builders/_internals/decimal128.d.ts +36 -0
  59. package/dist/schema-builders/_internals/decimal128.d.ts.map +1 -0
  60. package/dist/schema-builders/_internals/decimal128.js +38 -0
  61. package/dist/schema-builders/_internals/decimal128.js.map +1 -0
  62. package/dist/schema-builders/_internals/int32.d.ts +21 -0
  63. package/dist/schema-builders/_internals/int32.d.ts.map +1 -0
  64. package/dist/schema-builders/_internals/int32.js +29 -0
  65. package/dist/schema-builders/_internals/int32.js.map +1 -0
  66. package/dist/schema-builders/_internals/mixed.d.ts +9 -0
  67. package/dist/schema-builders/_internals/mixed.d.ts.map +1 -0
  68. package/dist/schema-builders/_internals/mixed.js +10 -0
  69. package/dist/schema-builders/_internals/mixed.js.map +1 -0
  70. package/dist/schema-builders/_internals/number.d.ts +21 -0
  71. package/dist/schema-builders/_internals/number.d.ts.map +1 -0
  72. package/dist/schema-builders/_internals/number.js +20 -0
  73. package/dist/schema-builders/_internals/number.js.map +1 -0
  74. package/dist/schema-builders/_internals/object-id.d.ts +9 -0
  75. package/dist/schema-builders/_internals/object-id.d.ts.map +1 -0
  76. package/dist/schema-builders/_internals/object-id.js +10 -0
  77. package/dist/schema-builders/_internals/object-id.js.map +1 -0
  78. package/dist/schema-builders/_internals/ref.d.ts +8 -0
  79. package/dist/schema-builders/_internals/ref.d.ts.map +1 -0
  80. package/dist/schema-builders/_internals/ref.js +13 -0
  81. package/dist/schema-builders/_internals/ref.js.map +1 -0
  82. package/dist/schema-builders/_internals/shared.d.ts +104 -0
  83. package/dist/schema-builders/_internals/shared.d.ts.map +1 -0
  84. package/dist/schema-builders/_internals/shared.js +128 -0
  85. package/dist/schema-builders/_internals/shared.js.map +1 -0
  86. package/dist/schema-builders/_internals/string.d.ts +37 -0
  87. package/dist/schema-builders/_internals/string.d.ts.map +1 -0
  88. package/dist/schema-builders/_internals/string.js +39 -0
  89. package/dist/schema-builders/_internals/string.js.map +1 -0
  90. package/dist/schema-builders/index.d.ts +12 -13
  91. package/dist/schema-builders/index.js +11 -13
  92. package/dist/transaction.d.ts +10 -0
  93. package/dist/transaction.d.ts.map +1 -0
  94. package/dist/transaction.js +9 -0
  95. package/dist/transaction.js.map +1 -0
  96. package/dist/types/data.d.ts +3 -5
  97. package/dist/types/data.d.ts.map +1 -1
  98. package/dist/types/index.d.ts +15 -11
  99. package/dist/types/index.d.ts.map +1 -1
  100. package/dist/types/paginate.d.ts +4 -19
  101. package/dist/types/paginate.d.ts.map +1 -1
  102. package/package.json +17 -19
  103. package/src/_internals.ts +31 -1
  104. package/src/assertions.ts +20 -11
  105. package/src/builders.ts +26 -18
  106. package/src/connection.ts +8 -2
  107. package/src/documents.ts +12 -0
  108. package/src/errors/duplicate-key.ts +14 -0
  109. package/src/errors/mongoose-update-conflict-error.ts +3 -0
  110. package/src/options.ts +31 -1
  111. package/src/plugins/assertions.ts +117 -49
  112. package/src/plugins/lean-decimal128-to-string.ts +47 -41
  113. package/src/plugins/normalize.ts +169 -99
  114. package/src/schema-builders/_internals/array.ts +15 -0
  115. package/src/schema-builders/_internals/boolean.ts +10 -0
  116. package/src/schema-builders/_internals/date.ts +11 -0
  117. package/src/schema-builders/_internals/decimal128.ts +79 -0
  118. package/src/schema-builders/_internals/int32.ts +58 -0
  119. package/src/schema-builders/_internals/mixed.ts +12 -0
  120. package/src/schema-builders/_internals/number.ts +71 -0
  121. package/src/schema-builders/_internals/object-id.ts +13 -0
  122. package/src/schema-builders/_internals/ref.ts +18 -0
  123. package/src/schema-builders/_internals/shared.ts +302 -0
  124. package/src/schema-builders/_internals/string.ts +113 -0
  125. package/src/schema-builders/index.ts +26 -35
  126. package/src/transaction.ts +22 -0
  127. package/src/types/data.ts +5 -10
  128. package/src/types/index.ts +32 -22
  129. package/src/types/paginate.ts +9 -24
  130. package/dist/schema-builders/_internals.d.ts +0 -18
  131. package/dist/schema-builders/_internals.d.ts.map +0 -1
  132. package/dist/schema-builders/_internals.js +0 -36
  133. package/dist/schema-builders/_internals.js.map +0 -1
  134. package/dist/schema-builders/base.d.ts +0 -5
  135. package/dist/schema-builders/base.d.ts.map +0 -1
  136. package/dist/schema-builders/base.js +0 -33
  137. package/dist/schema-builders/base.js.map +0 -1
  138. package/dist/schema-builders/bigint.d.ts +0 -39
  139. package/dist/schema-builders/bigint.d.ts.map +0 -1
  140. package/dist/schema-builders/bigint.js +0 -47
  141. package/dist/schema-builders/bigint.js.map +0 -1
  142. package/dist/schema-builders/boolean.d.ts +0 -33
  143. package/dist/schema-builders/boolean.d.ts.map +0 -1
  144. package/dist/schema-builders/boolean.js +0 -6
  145. package/dist/schema-builders/boolean.js.map +0 -1
  146. package/dist/schema-builders/date.d.ts +0 -49
  147. package/dist/schema-builders/date.d.ts.map +0 -1
  148. package/dist/schema-builders/date.js +0 -6
  149. package/dist/schema-builders/date.js.map +0 -1
  150. package/dist/schema-builders/decimal128.d.ts +0 -79
  151. package/dist/schema-builders/decimal128.d.ts.map +0 -1
  152. package/dist/schema-builders/decimal128.js +0 -47
  153. package/dist/schema-builders/decimal128.js.map +0 -1
  154. package/dist/schema-builders/double.d.ts +0 -39
  155. package/dist/schema-builders/double.d.ts.map +0 -1
  156. package/dist/schema-builders/double.js +0 -51
  157. package/dist/schema-builders/double.js.map +0 -1
  158. package/dist/schema-builders/int32.d.ts +0 -39
  159. package/dist/schema-builders/int32.d.ts.map +0 -1
  160. package/dist/schema-builders/int32.js +0 -47
  161. package/dist/schema-builders/int32.js.map +0 -1
  162. package/dist/schema-builders/mixed.d.ts +0 -33
  163. package/dist/schema-builders/mixed.d.ts.map +0 -1
  164. package/dist/schema-builders/mixed.js +0 -7
  165. package/dist/schema-builders/mixed.js.map +0 -1
  166. package/dist/schema-builders/number.d.ts +0 -49
  167. package/dist/schema-builders/number.d.ts.map +0 -1
  168. package/dist/schema-builders/number.js +0 -6
  169. package/dist/schema-builders/number.js.map +0 -1
  170. package/dist/schema-builders/object-id.d.ts +0 -43
  171. package/dist/schema-builders/object-id.d.ts.map +0 -1
  172. package/dist/schema-builders/object-id.js +0 -7
  173. package/dist/schema-builders/object-id.js.map +0 -1
  174. package/dist/schema-builders/ref.d.ts +0 -44
  175. package/dist/schema-builders/ref.d.ts.map +0 -1
  176. package/dist/schema-builders/ref.js +0 -10
  177. package/dist/schema-builders/ref.js.map +0 -1
  178. package/dist/schema-builders/string.d.ts +0 -138
  179. package/dist/schema-builders/string.d.ts.map +0 -1
  180. package/dist/schema-builders/string.js +0 -48
  181. package/dist/schema-builders/string.js.map +0 -1
  182. package/dist/schema-builders/uuid.d.ts +0 -33
  183. package/dist/schema-builders/uuid.d.ts.map +0 -1
  184. package/dist/schema-builders/uuid.js +0 -7
  185. package/dist/schema-builders/uuid.js.map +0 -1
  186. package/dist/types/_internals.d.ts +0 -24
  187. package/dist/types/_internals.d.ts.map +0 -1
  188. package/dist/types/_internals.js +0 -1
  189. package/dist/types/aggregate-paginate.d.ts +0 -82
  190. package/dist/types/aggregate-paginate.d.ts.map +0 -1
  191. package/dist/types/aggregate-paginate.js +0 -1
  192. package/dist/types/options.d.ts +0 -23
  193. package/dist/types/options.d.ts.map +0 -1
  194. package/dist/types/options.js +0 -1
  195. package/src/schema-builders/_internals.ts +0 -64
  196. package/src/schema-builders/base.ts +0 -57
  197. package/src/schema-builders/bigint.ts +0 -156
  198. package/src/schema-builders/boolean.ts +0 -45
  199. package/src/schema-builders/date.ts +0 -80
  200. package/src/schema-builders/decimal128.ts +0 -196
  201. package/src/schema-builders/double.ts +0 -166
  202. package/src/schema-builders/int32.ts +0 -157
  203. package/src/schema-builders/mixed.ts +0 -37
  204. package/src/schema-builders/number.ts +0 -80
  205. package/src/schema-builders/object-id.ts +0 -60
  206. package/src/schema-builders/ref.ts +0 -67
  207. package/src/schema-builders/string.ts +0 -258
  208. package/src/schema-builders/uuid.ts +0 -48
  209. package/src/types/_internals.ts +0 -27
  210. package/src/types/aggregate-paginate.ts +0 -115
  211. package/src/types/options.ts +0 -46
@@ -1,4 +1,6 @@
1
1
  import type {
2
+ ClientSession,
3
+ Model,
2
4
  mongo,
3
5
  MongooseUpdateQueryOptions,
4
6
  QueryFilter,
@@ -9,73 +11,139 @@ import type {
9
11
  } from 'mongoose';
10
12
 
11
13
  import { assertMongooseUpdateSuccess } from '../assertions';
14
+ import { MongooseUpdateConflictError } from '../errors/mongoose-update-conflict-error';
12
15
 
13
- declare module 'mongoose' {
14
- interface Document<
15
- T = Types.ObjectId,
16
- TQueryHelpers = any,
17
- DocType = any,
18
- TVirtuals = Record<string, any>,
19
- // eslint-disable-next-line ts/no-empty-object-type
20
- TSchemaOptions = {},
21
- > {
22
- assertUpdateSuccess: (
23
- update?:
24
- | UpdateQuery<Document<T, TQueryHelpers, DocType, TVirtuals, TSchemaOptions>>
25
- | UpdateWithAggregationPipeline,
26
- options?: null | QueryOptions,
27
- expectedModifiedCount?: number,
28
- ) => Promise<void>;
29
- }
16
+ type UpdateIfUnmodified<RawDocType, Result> = (
17
+ updatedAt: Date | number | string,
18
+ update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,
19
+ options?: UpdateIfUnmodifiedOptions,
20
+ ) => Promise<Result>;
21
+
22
+ export interface MongooseAssertionsDocumentMethods<RawDocType> {
23
+ /**
24
+ * @throws {MongooseUpdateConflictError} If the document was changed or deleted after `updatedAt`.
25
+ */
26
+ assertUpdateIfUnmodified: UpdateIfUnmodified<RawDocType, void>;
27
+ assertUpdateSuccess: (
28
+ update?: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,
29
+ options?: null | QueryOptions,
30
+ ) => Promise<void>;
31
+
32
+ /**
33
+ * Updates the document only if its `updatedAt` timestamp still equals `updatedAt`, in one atomic `updateOne`, and
34
+ * returns whether it did. Every update through Mongoose sets a new `updatedAt`, so any change in between, or a
35
+ * deletion, makes it return `false`; timestamps have millisecond precision, so two writes within the same
36
+ * millisecond are not told apart. Uses `options.session` if given, otherwise the document's session.
37
+ *
38
+ * @throws {Error} If the schema has no `updatedAt` timestamp or the document has no `_id`.
39
+ */
40
+ updateIfUnmodified: UpdateIfUnmodified<RawDocType, boolean>;
41
+ }
30
42
 
31
- interface Model<
32
- TRawDocType,
33
- // eslint-disable-next-line ts/no-empty-object-type
34
- TQueryHelpers = {},
35
- // eslint-disable-next-line ts/no-empty-object-type
36
- TInstanceMethods = {},
37
- // eslint-disable-next-line ts/no-empty-object-type
38
- TVirtuals = {},
39
- // eslint-disable-next-line unused-imports/no-unused-vars
40
- THydratedDocumentType = HydratedDocument<TRawDocType, TInstanceMethods & TVirtuals, TQueryHelpers, TVirtuals>,
41
- // eslint-disable-next-line unused-imports/no-unused-vars
42
- TSchema = any,
43
- > {
44
- assertUpdateSuccess: (
45
- filter: QueryFilter<TRawDocType>,
46
- update: UpdateQuery<TRawDocType> | UpdateWithAggregationPipeline,
47
- options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<TRawDocType>) | null,
48
- expectedModifiedCount?: number,
49
- ) => Promise<void>;
43
+ export interface MongooseAssertionsModelStatics<RawDocType> {
44
+ assertUpdateManySuccess: (
45
+ filter: QueryFilter<RawDocType>,
46
+ update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,
47
+ options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<RawDocType>) | null,
48
+ minModifiedCount?: number,
49
+ ) => Promise<void>;
50
+
51
+ assertUpdateOneSuccess: (
52
+ filter: QueryFilter<RawDocType>,
53
+ update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,
54
+ options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<RawDocType>) | null,
55
+ ) => Promise<void>;
56
+ }
57
+
58
+ /**
59
+ * Only the session is configurable: other update options such as `upsert` or `timestamps` would break the guarantee
60
+ * that a successful update writes a new `updatedAt`.
61
+ */
62
+ export interface UpdateIfUnmodifiedOptions {
63
+ session?: ClientSession | null;
64
+ }
65
+
66
+ interface UpdateIfUnmodifiedThis {
67
+ $session: () => ClientSession | null;
68
+ _id: unknown;
69
+ constructor: Model<any>;
70
+ }
71
+
72
+ function getUpdatedAtPath(schema: Schema) {
73
+ const timestamps = schema.get('timestamps');
74
+ let path: unknown;
75
+ if (timestamps === true) path = 'updatedAt';
76
+ else if (timestamps && typeof timestamps === 'object') {
77
+ path = timestamps.updatedAt === true || !('updatedAt' in timestamps) ? 'updatedAt' : timestamps.updatedAt;
50
78
  }
79
+
80
+ // Mongoose skips timestamp paths it cannot name, e.g. `{ updatedAt: '' }`, so require the path to exist.
81
+ if (typeof path === 'string' && schema.path(path)) return path;
82
+ throw new Error('updateIfUnmodified requires the schema to have an updatedAt timestamp');
51
83
  }
52
84
 
53
- export function mongooseAssertionsPlugin<S extends Schema>(schema: S) {
85
+ export function mongooseAssertionsPlugin(schema: Schema) {
86
+ schema.method('updateIfUnmodified', updateIfUnmodified);
87
+ schema.method(
88
+ 'assertUpdateIfUnmodified',
89
+ async function (this: UpdateIfUnmodifiedThis, ...args: Parameters<UpdateIfUnmodified<any, void>>) {
90
+ if (await updateIfUnmodified.apply(this, args)) return;
91
+ throw new MongooseUpdateConflictError('Document was modified or deleted');
92
+ },
93
+ );
94
+
54
95
  schema.method(
55
96
  'assertUpdateSuccess',
97
+ async function (update?: UpdateQuery<any> | UpdateWithAggregationPipeline, options?: null | QueryOptions) {
98
+ return await assertMongooseUpdateSuccess(this.updateOne(update, options));
99
+ },
100
+ );
101
+
102
+ schema.static(
103
+ 'assertUpdateManySuccess',
56
104
  async function (
57
- update?: UpdateQuery<any> | UpdateWithAggregationPipeline,
58
- options?: null | QueryOptions,
59
- expectedModifiedCount?: number,
105
+ filter: QueryFilter<any>,
106
+ update: UpdateQuery<any> | UpdateWithAggregationPipeline,
107
+ options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<any>) | null,
108
+ minModifiedCount?: number,
60
109
  ) {
61
- return await assertMongooseUpdateSuccess(this.updateOne(update, options), expectedModifiedCount);
110
+ return await assertMongooseUpdateSuccess(this.updateMany(filter, update, options), minModifiedCount);
62
111
  },
63
112
  );
64
113
 
65
114
  schema.static(
66
- 'assertUpdateSuccess',
115
+ 'assertUpdateOneSuccess',
67
116
  async function (
68
117
  filter: QueryFilter<any>,
69
118
  update: UpdateQuery<any> | UpdateWithAggregationPipeline,
70
119
  options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<any>) | null,
71
- expectedModifiedCount: number = 1,
72
120
  ) {
73
- return await assertMongooseUpdateSuccess(
74
- expectedModifiedCount === 1
75
- ? this.updateOne(filter, update, options)
76
- : this.updateMany(filter, update, options),
77
- expectedModifiedCount,
78
- );
121
+ return await assertMongooseUpdateSuccess(this.updateOne(filter, update, options));
79
122
  },
80
123
  );
81
124
  }
125
+
126
+ async function updateIfUnmodified(
127
+ this: UpdateIfUnmodifiedThis,
128
+ updatedAt: Date | number | string,
129
+ update: UpdateQuery<any> | UpdateWithAggregationPipeline,
130
+ options?: UpdateIfUnmodifiedOptions,
131
+ ) {
132
+ // With `ignoreUndefined`, an undefined `_id` would be dropped from the filter and match another document.
133
+ if (this._id === null || this._id === undefined) throw new Error('updateIfUnmodified requires the document _id');
134
+ const session = options && 'session' in options ? options.session : this.$session() ?? undefined;
135
+ const model = this.constructor;
136
+ const result = await model.updateOne(
137
+ {
138
+ _id: this._id,
139
+ [getUpdatedAtPath(model.schema)]: updatedAt,
140
+ },
141
+ update,
142
+ // Without a session the key is omitted, so `transactionAsyncLocalStorage` can still supply one. An explicit
143
+ // `null` opts out of any session, as Mongoose's own options do, although its types only allow `undefined`.
144
+ session === undefined ? undefined : { session: session as ClientSession },
145
+ );
146
+
147
+ if (!result.acknowledged) throw new Error('Update was not acknowledged');
148
+ return result.matchedCount === 1;
149
+ }
@@ -10,58 +10,55 @@ import {
10
10
  objectValues,
11
11
  } from 'ts-extras';
12
12
 
13
+ import { decimal128ToPlainString } from '../_internals';
14
+
13
15
  declare module 'mongoose' {
14
16
  interface LeanOptions {
15
- /**
16
- * Override conversion of marked Decimal128 fields. Defaults to the plugin's enabledByDefault setting.
17
- */
18
17
  decimal128ToString?: boolean;
19
18
  }
20
19
  }
21
20
 
22
- type QueryWithOptionalMap = Query<unknown, unknown> & { map?: (transform: (result: unknown) => unknown) => unknown };
23
-
24
21
  export interface MongooseLeanDecimal128ToStringPluginOptions {
25
- /**
26
- * Whether marked fields are converted on lean queries by default. Defaults to true.
27
- */
28
22
  enabledByDefault?: boolean;
29
23
  }
30
24
 
31
- // Constants/Variables
25
+ const conversionPathsCache = new WeakMap<Schema, Array<[pathSegments: string[], schemaType: SchemaType]>>();
32
26
  const registeredSchemas = new WeakSet<Schema>();
33
27
 
34
- // Functions
35
28
  const isNonNullObject = (value: unknown): value is Record<string, any> => value !== null && typeof value === 'object';
36
29
 
30
+ function canContainMarkedDecimal128(schemaType: SchemaType): boolean {
31
+ // Subdocument schemas are filtered by their own cached paths when converted.
32
+ if (schemaType.schema) return true;
33
+ if (schemaType.instance === 'Decimal128') return schemaType.options.leanDecimal128ToString === true;
34
+ const embeddedSchemaType = schemaType.getEmbeddedSchemaType();
35
+ return !!embeddedSchemaType && canContainMarkedDecimal128(embeddedSchemaType);
36
+ }
37
+
37
38
  function convertDocument(schema: Schema, value: unknown) {
38
39
  if (!isNonNullObject(value)) return;
39
40
  const discriminatorKey = schema.get('discriminatorKey') ?? '__t';
40
- const discriminatorSchema = objectValues(schema.discriminators ?? {}).find(
41
+ const discriminatorSchema = schema.discriminators && objectValues(schema.discriminators).find(
41
42
  (childSchema) => childSchema.get('discriminatorKey') === discriminatorKey
42
43
  && (childSchema as Schema & { discriminatorMapping?: { value: unknown } }).discriminatorMapping?.value
43
44
  === value[discriminatorKey],
44
45
  );
45
46
 
46
- const documentSchema = discriminatorSchema ?? schema;
47
- documentSchema.eachPath((path, schemaType) => {
48
- // Maps are handled through their embedded schema type, not their synthetic $* path.
49
- const pathSegments = path.split('.');
50
- if (pathSegments.includes('$*')) return;
51
- convertPath(value, pathSegments, schemaType);
52
- });
47
+ for (const [pathSegments, schemaType] of getConversionPaths(discriminatorSchema ?? schema)) {
48
+ convertPath(value, pathSegments, 0, schemaType);
49
+ }
53
50
  }
54
51
 
55
- function convertPath(value: unknown, pathSegments: string[], schemaType: SchemaType) {
52
+ function convertPath(value: unknown, pathSegments: string[], index: number, schemaType: SchemaType) {
56
53
  if (Array.isArray(value)) {
57
- value.forEach((item) => convertPath(item, pathSegments, schemaType));
54
+ value.forEach((item) => convertPath(item, pathSegments, index, schemaType));
58
55
  return;
59
56
  }
60
57
 
61
58
  if (!isNonNullObject(value)) return;
62
- const [key, ...remainingPathSegments] = pathSegments;
59
+ const key = pathSegments[index];
63
60
  if (key === undefined || !objectHasOwn(value, key)) return;
64
- if (remainingPathSegments.length) convertPath(value[key], remainingPathSegments, schemaType);
61
+ if (index < pathSegments.length - 1) convertPath(value[key], pathSegments, index + 1, schemaType);
65
62
  else value[key] = convertValue(value[key], schemaType);
66
63
  }
67
64
 
@@ -95,22 +92,34 @@ function convertValue(value: unknown, schemaType: SchemaType): unknown {
95
92
  && schemaType.options.leanDecimal128ToString === true
96
93
  && isNonNullObject(value)
97
94
  && value._bsontype === 'Decimal128'
98
- && typeof value.toString === 'function'
99
- ) return (value as Types.Decimal128).toString();
95
+ ) return decimal128ToPlainString(value as Types.Decimal128);
100
96
 
101
97
  return value;
102
98
  }
103
99
 
100
+ function getConversionPaths(schema: Schema) {
101
+ let conversionPaths = conversionPathsCache.get(schema);
102
+ if (conversionPaths) return conversionPaths;
103
+ conversionPaths = [];
104
+ schema.eachPath((path, schemaType) => {
105
+ // Maps are handled through their embedded schema type, not their synthetic $* path.
106
+ const pathSegments = path.split('.');
107
+ if (!pathSegments.includes('$*') && canContainMarkedDecimal128(schemaType)) {
108
+ conversionPaths.push([
109
+ pathSegments,
110
+ schemaType,
111
+ ]);
112
+ }
113
+ });
114
+
115
+ conversionPathsCache.set(schema, conversionPaths);
116
+ return conversionPaths;
117
+ }
118
+
104
119
  /**
105
- * Converts marked Decimal128 fields to strings on lean queries without invoking getters.
106
- *
107
- * @remarks
108
- * `decimal128().setToStringGetter` sets the `leanDecimal128ToString` schema-path option.
109
- * Query-level `lean({ decimal128ToString: false })` disables this plugin only, not other plugins.
110
- * Existing strings and nullish values are preserved. Missing/projected-out fields are not added.
111
- * Supports nested schemas, arrays and maps. Aggregate results are intentionally not transformed.
112
- * Registration is idempotent; the first registration's default options take precedence.
113
- * Runtime conversion does not override Mongoose's inferred lean result types.
120
+ * Converts paths marked by `s.decimal128().setToStringGetter()` on lean queries, except with
121
+ * `lean({ decimal128ToString: false })` and in aggregate results.
122
+ * Convertible paths are collected per schema on its first converted query; paths added later are ignored.
114
123
  */
115
124
  export function mongooseLeanDecimal128ToStringPlugin(
116
125
  schema: Schema,
@@ -119,7 +128,7 @@ export function mongooseLeanDecimal128ToStringPlugin(
119
128
  if (registeredSchemas.has(schema)) return;
120
129
  registeredSchemas.add(schema);
121
130
 
122
- function convertResult(query: QueryWithOptionalMap, result: unknown) {
131
+ function convertResult(query: Query<unknown, unknown>, result: unknown) {
123
132
  const leanOptions = query.mongooseOptions().lean;
124
133
  if (!leanOptions) return result;
125
134
  const conversionEnabled = typeof leanOptions === 'object'
@@ -135,14 +144,11 @@ export function mongooseLeanDecimal128ToStringPlugin(
135
144
  return result;
136
145
  }
137
146
 
138
- // Find cursors do not run post('find'); match Mongoose's query/cursor transform surfaces.
147
+ // `Query#transform` also applies to cursors, which do not run post('find') hooks.
139
148
  schema.pre(
140
149
  'find',
141
- function (this: QueryWithOptionalMap) {
142
- const transform = (result: unknown) => convertResult(this, result);
143
- if (typeof this.map === 'function') this.map(transform);
144
- else if (typeof this.transform === 'function') this.transform(transform);
145
- else this.setOptions({ transform });
150
+ function (this: Query<unknown, unknown>) {
151
+ this.transform((result) => convertResult(this, result));
146
152
  },
147
153
  );
148
154
 
@@ -153,7 +159,7 @@ export function mongooseLeanDecimal128ToStringPlugin(
153
159
  'findOneAndDelete',
154
160
  'findOneAndReplace',
155
161
  ],
156
- function (this: QueryWithOptionalMap, result: unknown) {
162
+ function (this: Query<unknown, unknown>, result: unknown) {
157
163
  convertResult(this, result);
158
164
  },
159
165
  );
@@ -3,123 +3,193 @@ import {
3
3
  set as setProp,
4
4
  unset as unsetProp,
5
5
  } from 'es-toolkit/compat';
6
- import { Types } from 'mongoose';
7
- import type { Schema } from 'mongoose';
8
- import { objectEntries } from 'ts-extras';
9
-
10
- export interface MongooseNormalizePluginOptions {
11
- /**
12
- * Whether to move the serialized `_id` value to `id`.
13
- *
14
- * @remarks
15
- * If `false`, preserves the value under `_id` instead. Only values other than `undefined` are copied.
16
- *
17
- * @defaultValue `true`.
18
- */
19
- convertIdField?: boolean;
20
-
21
- /**
22
- * Register normalization on child schemas too. Defaults to true.
23
- */
24
- recursive?: boolean;
25
-
26
- /**
27
- * Whether to convert a serialized `ObjectId` identifier to its hexadecimal string.
28
- *
29
- * @remarks
30
- * Applies before choosing the `id` or `_id` output key. Identifiers of other types are unchanged.
31
- *
32
- * @defaultValue `true`.
33
- */
34
- toHexIdIfObjectId?: boolean;
6
+ import {
7
+ Model,
8
+ Schema,
9
+ Types,
10
+ } from 'mongoose';
11
+ import type {
12
+ Document,
13
+ SchemaType,
14
+ } from 'mongoose';
15
+ import {
16
+ objectEntries,
17
+ objectFromEntries,
18
+ objectValues,
19
+ } from 'ts-extras';
20
+
21
+ import { decimal128ToPlainString } from '../_internals';
22
+
23
+ type DiscriminatorFunction = (name: unknown, schema: unknown, ...args: unknown[]) => unknown;
24
+ type DiscriminatorMap = Record<string, { schema: Schema }>;
25
+
26
+ interface NormalizedPaths {
27
+ decimal128Paths: Array<[path: string, schemaType: SchemaType]>;
28
+ privatePaths: string[];
35
29
  }
36
30
 
37
- // Constants/Variables
31
+ const normalizedPathsCache = new WeakMap<Schema, NormalizedPaths>();
32
+ const normalizeTransforms = new WeakSet<object>();
38
33
  const registeredSchemas = new WeakSet<Schema>();
39
34
 
40
- // Functions
35
+ const isNonNullObject = (value: unknown): value is Record<string, any> => value !== null && typeof value === 'object';
41
36
 
42
- /**
43
- * Registers JSON normalization on a Mongoose schema.
44
- *
45
- * @remarks
46
- * Mutates the schema's `toJSON` configuration while preserving its other options. The transform removes `__v`,
47
- * normalizes `_id` according to the plugin options, removes schema paths marked `private`, and converts
48
- * truthy serialized values at registered `Decimal128` paths to strings.
49
- *
50
- * If an existing transform is a function, invokes it after normalization. If it returns `undefined`,
51
- * preserves the normalized output and any mutations made by that transform; otherwise, uses its return value.
52
- * That transform can change the normalized output, and its errors propagate during serialization.
53
- * Registers itself on child schemas unless `recursive` is false. Does not configure `toObject`.
54
- * Registration is idempotent per schema; the first registration's options take precedence.
55
- *
56
- * @param schema - The schema whose JSON serialization configuration is modified.
57
- * @param pluginOptions - The normalization and registration options; omitted options use their documented defaults.
58
- */
59
- export function mongooseNormalizePlugin<S extends Schema>(
60
- schema: S,
61
- pluginOptions?: MongooseNormalizePluginOptions,
62
- ) {
63
- if (registeredSchemas.has(schema)) return;
64
- registeredSchemas.add(schema);
37
+ function containsDecimal128(schemaType: SchemaType): boolean {
38
+ if (schemaType.instance === 'Decimal128') return true;
39
+ const embeddedSchemaType = schemaType.getEmbeddedSchemaType();
40
+ // Subdocuments are normalized by their own schema's transform.
41
+ return !!embeddedSchemaType && !embeddedSchemaType.schema && containsDecimal128(embeddedSchemaType);
42
+ }
43
+
44
+ function decimal128ToString(value: unknown, schemaType: SchemaType): unknown {
45
+ if (schemaType.instance === 'Decimal128') {
46
+ // `flattenDecimals` serializes to `{ $numberDecimal }`; getters may return plain values.
47
+ if (isNonNullObject(value)) {
48
+ if (value._bsontype === 'Decimal128') return decimal128ToPlainString(value as Types.Decimal128);
49
+ return typeof value.$numberDecimal === 'string' ? decimal128ToPlainString(value.$numberDecimal) : value;
50
+ }
51
+
52
+ return typeof value === 'bigint' || typeof value === 'number' ? String(value) : value;
53
+ }
54
+
55
+ const embeddedSchemaType = schemaType.getEmbeddedSchemaType();
56
+ if (!embeddedSchemaType) return value;
57
+ if (Array.isArray(value)) return value.map((item) => decimal128ToString(item, embeddedSchemaType));
58
+ if (schemaType.instance !== 'Map') return value;
59
+ if (value instanceof Map) {
60
+ return new Map(Array.from(
61
+ value,
62
+ ([key, item]) => [
63
+ key,
64
+ decimal128ToString(item, embeddedSchemaType),
65
+ ],
66
+ ));
67
+ }
68
+
69
+ if (isNonNullObject(value)) {
70
+ return objectFromEntries(
71
+ objectEntries(value).map(([key, item]) => [
72
+ key,
73
+ decimal128ToString(item, embeddedSchemaType),
74
+ ]),
75
+ );
76
+ }
77
+
78
+ return value;
79
+ }
80
+
81
+ function getNormalizedPaths(schema: Schema) {
82
+ let normalizedPaths = normalizedPathsCache.get(schema);
83
+ if (normalizedPaths) return normalizedPaths;
84
+ normalizedPaths = {
85
+ decimal128Paths: [],
86
+ privatePaths: [],
87
+ };
65
88
 
66
- // Collect special paths (Decimal128 & private)
67
- const decimalPaths: string[] = [];
68
- const privatePaths: string[] = [];
69
89
  for (const [path, schemaType] of objectEntries(schema.paths)) {
70
- if (schemaType?.options?.private) privatePaths.push(path);
71
- else if (schemaType?.instance === 'Decimal128') decimalPaths.push(path);
90
+ // Map values are handled through the map path's embedded schema type, not the synthetic `$*` path.
91
+ if (path.split('.').includes('$*')) continue;
92
+ if (schemaType.options?.private) normalizedPaths.privatePaths.push(path);
93
+ else if (containsDecimal128(schemaType)) {
94
+ normalizedPaths.decimal128Paths.push([
95
+ path,
96
+ schemaType,
97
+ ]);
98
+ }
72
99
  }
73
100
 
74
- // Get original toJSON configuration
101
+ normalizedPathsCache.set(schema, normalizedPaths);
102
+ return normalizedPaths;
103
+ }
104
+
105
+ /**
106
+ * Child and discriminator schemas are registered too, so register after the schema's paths are defined.
107
+ * `toJSON` options cannot be changed afterwards.
108
+ */
109
+ export function mongooseNormalizePlugin(schema: Schema) {
110
+ if (registeredSchemas.has(schema)) return;
111
+ registeredSchemas.add(schema);
75
112
  const toJson = schema.get('toJSON');
76
113
  const toJsonTransform = toJson?.transform;
77
-
78
- // Override toJSON with custom transform
79
- schema.set(
80
- 'toJSON',
81
- {
114
+ // Discriminator schemas may inherit the base transform, which already uses each document's own schema.
115
+ if (typeof toJsonTransform !== 'function' || !normalizeTransforms.has(toJsonTransform)) {
116
+ // Not `Schema#set`: it copies the options minus the transform onto implicitly created child schemas, which may
117
+ // already be registered and shared with a discriminator's base schema.
118
+ schema.options.toJSON = {
82
119
  ...toJson,
83
120
  transform(doc, ret, options) {
84
- // Copy object and remove __v
85
- const copiedRet = { ...ret };
86
- // @ts-expect-error Ignore this error
87
- delete copiedRet.__v;
88
-
89
- // Normalize _id (convert to hex and/or move to id)
90
- let _id = copiedRet._id;
91
- delete copiedRet._id;
92
- if (pluginOptions?.toHexIdIfObjectId !== false && _id instanceof Types.ObjectId) {
93
- _id = _id.toHexString();
94
- }
95
-
96
- if (_id !== undefined) {
97
- if (pluginOptions?.convertIdField !== false) copiedRet.id = _id;
98
- else copiedRet._id = _id;
99
- }
121
+ normalize(doc, ret);
122
+ if (typeof toJsonTransform !== 'function') return ret;
123
+ const transformed = toJsonTransform(doc, ret, options);
124
+ return transformed === undefined ? ret : transformed;
125
+ },
126
+ };
100
127
 
101
- // Remove private fields
102
- for (const path of privatePaths) unsetProp(copiedRet, path);
128
+ const transform = schema.options.toJSON.transform;
129
+ if (typeof transform === 'function') normalizeTransforms.add(transform);
130
+ }
103
131
 
104
- // Convert Decimal128 fields to string
105
- for (const path of decimalPaths) {
106
- const value = getProp(copiedRet, path) as Types.Decimal128 | undefined;
107
- if (value) setProp(copiedRet, path, value.toString());
132
+ const childSchemas = new Set<Schema>(schema.childSchemas.map(({ schema: child }) => child));
133
+ objectValues(schema.discriminators ?? {}).forEach((child) => childSchemas.add(child));
134
+ for (const pathSchemaType of objectValues(schema.paths)) {
135
+ // `childSchemas` omits subdocuments nested in arrays of arrays or maps of arrays.
136
+ let schemaType: SchemaType | undefined = pathSchemaType;
137
+ while (schemaType) {
138
+ const embedded = schemaType as SchemaType & {
139
+ Constructor?: { discriminators?: DiscriminatorMap };
140
+ discriminator?: DiscriminatorFunction;
141
+ };
142
+
143
+ if (embedded.schema) {
144
+ childSchemas.add(embedded.schema);
145
+ if (typeof embedded.discriminator === 'function') {
146
+ embedded.discriminator = registerAfterDiscriminator(embedded.discriminator);
108
147
  }
148
+ }
109
149
 
110
- // Run original toJSON transform
111
- if (toJsonTransform && typeof toJsonTransform !== 'boolean') {
112
- const transformed = toJsonTransform(doc as any, copiedRet as any, options as any);
113
- return transformed === undefined ? copiedRet : transformed;
114
- }
150
+ // Embedded discriminators live on the path's constructor; `schema.discriminators` is keyed by name only,
151
+ // so paths sharing a schema overwrite each other there.
152
+ objectValues(embedded.Constructor?.discriminators ?? {}).forEach((child) => childSchemas.add(child.schema));
153
+ schemaType = schemaType.getEmbeddedSchemaType();
154
+ }
155
+ }
115
156
 
116
- // Return normalized object
117
- return copiedRet;
118
- },
119
- },
120
- );
157
+ childSchemas.forEach((child) => child.plugin(mongooseNormalizePlugin));
158
+ schema.static('discriminator', registerAfterDiscriminator(Model.discriminator));
159
+ // `Schema#set` replaces the whole `toJSON` object, which would drop the normalize transform.
160
+ const set = schema.set;
161
+ schema.set = function (this: Schema, ...args: Parameters<Schema['set']>) {
162
+ if (args[0] === 'toJSON' && args.length > 1) {
163
+ throw new Error('toJSON options cannot be changed after mongooseNormalizePlugin is registered.');
164
+ }
165
+
166
+ return set.apply(this, args);
167
+ } as Schema['set'];
168
+ }
121
169
 
122
- if (pluginOptions?.recursive !== false) {
123
- schema.childSchemas.forEach(({ schema: child }) => child.plugin(mongooseNormalizePlugin, pluginOptions));
170
+ function normalize(doc: Document<unknown>, ret: Record<string, any>) {
171
+ // A data field named `schema` shadows `Document#schema`; the constructor holds the schema Mongoose serializes with.
172
+ const schema = (doc.constructor as { schema?: Schema }).schema ?? doc.schema;
173
+ const { decimal128Paths, privatePaths } = getNormalizedPaths(schema);
174
+ const versionKey = schema.get('versionKey');
175
+ if (typeof versionKey === 'string') unsetProp(ret, versionKey);
176
+ const _id = ret._id;
177
+ delete ret._id;
178
+ if (_id !== undefined) ret.id = _id instanceof Types.ObjectId ? _id.toHexString() : _id;
179
+ for (const path of privatePaths) unsetProp(ret, path);
180
+ for (const [path, schemaType] of decimal128Paths) {
181
+ const value = getProp(ret, path);
182
+ if (value !== undefined) setProp(ret, path, decimal128ToString(value, schemaType));
124
183
  }
125
184
  }
185
+
186
+ // Mongoose clones and merges the discriminator schema, so register on the schema it actually uses. Registering before
187
+ // the merge would give a schema without its own `toJSON` one, which replaces the inherited options.
188
+ function registerAfterDiscriminator<T extends (...args: any[]) => any>(discriminator: T) {
189
+ return function (this: unknown, ...args: Parameters<T>): ReturnType<T> {
190
+ const result = discriminator.apply(this, args);
191
+ const { schema } = result as { schema?: unknown };
192
+ if (schema instanceof Schema) schema.plugin(mongooseNormalizePlugin);
193
+ return result;
194
+ };
195
+ }