@kikiutils/mongoose 7.1.0 → 9.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 (113) hide show
  1. package/README.md +8 -8
  2. package/dist/_internals.d.ts +4 -0
  3. package/dist/_internals.d.ts.map +1 -1
  4. package/dist/_internals.js +2 -1
  5. package/dist/_internals.js.map +1 -1
  6. package/dist/builders.d.ts +1 -3
  7. package/dist/builders.d.ts.map +1 -1
  8. package/dist/builders.js +8 -9
  9. package/dist/builders.js.map +1 -1
  10. package/dist/connection.d.ts +5 -0
  11. package/dist/connection.d.ts.map +1 -0
  12. package/dist/connection.js +10 -0
  13. package/dist/connection.js.map +1 -0
  14. package/dist/options.d.ts.map +1 -1
  15. package/dist/options.js +2 -1
  16. package/dist/options.js.map +1 -1
  17. package/dist/plugins/lean-decimal128-to-string.d.ts +26 -0
  18. package/dist/plugins/lean-decimal128-to-string.d.ts.map +1 -0
  19. package/dist/plugins/lean-decimal128-to-string.js +85 -0
  20. package/dist/plugins/lean-decimal128-to-string.js.map +1 -0
  21. package/dist/plugins/normalize.d.ts +24 -14
  22. package/dist/plugins/normalize.d.ts.map +1 -1
  23. package/dist/plugins/normalize.js +20 -10
  24. package/dist/plugins/normalize.js.map +1 -1
  25. package/dist/schema-builders/base.d.ts +1 -1
  26. package/dist/schema-builders/base.d.ts.map +1 -1
  27. package/dist/schema-builders/base.js.map +1 -1
  28. package/dist/schema-builders/bigint.d.ts +60 -0
  29. package/dist/schema-builders/bigint.d.ts.map +1 -0
  30. package/dist/schema-builders/bigint.js +58 -0
  31. package/dist/schema-builders/bigint.js.map +1 -0
  32. package/dist/schema-builders/boolean.d.ts.map +1 -1
  33. package/dist/schema-builders/boolean.js.map +1 -1
  34. package/dist/schema-builders/date.d.ts +2 -2
  35. package/dist/schema-builders/date.d.ts.map +1 -1
  36. package/dist/schema-builders/date.js.map +1 -1
  37. package/dist/schema-builders/decimal128.d.ts +20 -14
  38. package/dist/schema-builders/decimal128.d.ts.map +1 -1
  39. package/dist/schema-builders/decimal128.js +1 -0
  40. package/dist/schema-builders/decimal128.js.map +1 -1
  41. package/dist/schema-builders/double.d.ts +60 -0
  42. package/dist/schema-builders/double.d.ts.map +1 -0
  43. package/dist/schema-builders/double.js +62 -0
  44. package/dist/schema-builders/double.js.map +1 -0
  45. package/dist/schema-builders/index.d.ts +6 -1
  46. package/dist/schema-builders/index.js +6 -1
  47. package/dist/schema-builders/int32.d.ts +60 -0
  48. package/dist/schema-builders/int32.d.ts.map +1 -0
  49. package/dist/schema-builders/int32.js +58 -0
  50. package/dist/schema-builders/int32.js.map +1 -0
  51. package/dist/schema-builders/mixed.d.ts +34 -0
  52. package/dist/schema-builders/mixed.d.ts.map +1 -0
  53. package/dist/schema-builders/mixed.js +8 -0
  54. package/dist/schema-builders/mixed.js.map +1 -0
  55. package/dist/schema-builders/number.d.ts +2 -2
  56. package/dist/schema-builders/number.d.ts.map +1 -1
  57. package/dist/schema-builders/number.js.map +1 -1
  58. package/dist/schema-builders/object-id.d.ts +2 -2
  59. package/dist/schema-builders/object-id.d.ts.map +1 -1
  60. package/dist/schema-builders/object-id.js.map +1 -1
  61. package/dist/schema-builders/ref.d.ts +2 -2
  62. package/dist/schema-builders/ref.d.ts.map +1 -1
  63. package/dist/schema-builders/ref.js.map +1 -1
  64. package/dist/schema-builders/string.d.ts +35 -25
  65. package/dist/schema-builders/string.d.ts.map +1 -1
  66. package/dist/schema-builders/string.js.map +1 -1
  67. package/dist/schema-builders/uuid.d.ts +34 -0
  68. package/dist/schema-builders/uuid.d.ts.map +1 -0
  69. package/dist/schema-builders/uuid.js +8 -0
  70. package/dist/schema-builders/uuid.js.map +1 -0
  71. package/dist/types/aggregate-paginate.d.ts +24 -8
  72. package/dist/types/aggregate-paginate.d.ts.map +1 -1
  73. package/dist/types/index.d.ts +1 -4
  74. package/dist/types/index.d.ts.map +1 -1
  75. package/dist/types/options.d.ts +9 -4
  76. package/dist/types/options.d.ts.map +1 -1
  77. package/dist/types/paginate.d.ts +6 -2
  78. package/dist/types/paginate.d.ts.map +1 -1
  79. package/package.json +17 -12
  80. package/src/_internals.ts +3 -0
  81. package/src/builders.ts +18 -32
  82. package/src/connection.ts +14 -0
  83. package/src/options.ts +8 -1
  84. package/src/plugins/lean-decimal128-to-string.ts +149 -0
  85. package/src/plugins/normalize.ts +39 -15
  86. package/src/schema-builders/base.ts +6 -1
  87. package/src/schema-builders/bigint.ts +190 -0
  88. package/src/schema-builders/boolean.ts +1 -4
  89. package/src/schema-builders/date.ts +2 -2
  90. package/src/schema-builders/decimal128.ts +21 -14
  91. package/src/schema-builders/double.ts +198 -0
  92. package/src/schema-builders/index.ts +15 -0
  93. package/src/schema-builders/int32.ts +191 -0
  94. package/src/schema-builders/mixed.ts +37 -0
  95. package/src/schema-builders/number.ts +2 -2
  96. package/src/schema-builders/object-id.ts +2 -2
  97. package/src/schema-builders/ref.ts +2 -2
  98. package/src/schema-builders/string.ts +35 -25
  99. package/src/schema-builders/uuid.ts +48 -0
  100. package/src/types/aggregate-paginate.ts +29 -8
  101. package/src/types/index.ts +0 -5
  102. package/src/types/options.ts +12 -3
  103. package/src/types/paginate.ts +6 -2
  104. package/dist/constants.d.ts +0 -5
  105. package/dist/constants.d.ts.map +0 -1
  106. package/dist/constants.js +0 -6
  107. package/dist/constants.js.map +0 -1
  108. package/dist/helpers.d.ts +0 -5
  109. package/dist/helpers.d.ts.map +0 -1
  110. package/dist/helpers.js +0 -9
  111. package/dist/helpers.js.map +0 -1
  112. package/src/constants.ts +0 -3
  113. package/src/helpers.ts +0 -5
package/src/_internals.ts CHANGED
@@ -1,3 +1,6 @@
1
+ import type { Connection } from 'mongoose';
2
+
1
3
  import type { CustomMongooseOptions } from './types/options';
2
4
 
3
5
  export const customMongooseOptions: CustomMongooseOptions = {};
6
+ export const mongooseConnectionState: { defaultConnection?: Connection } = {};
package/src/builders.ts CHANGED
@@ -1,16 +1,12 @@
1
- import mongoose from 'mongoose';
2
- import type {
3
- Model as MongooseModel,
4
- Schema,
5
- } from 'mongoose';
1
+ import type { Schema } from 'mongoose';
6
2
  import mongooseAggregatePaginate from 'mongoose-aggregate-paginate-v2';
7
3
  import mongoosePaginate from 'mongoose-paginate-v2';
8
4
 
9
5
  import { customMongooseOptions } from './_internals';
10
- import { mongooseConnections } from './constants';
6
+ import { getDefaultMongooseConnection } from './connection';
11
7
  import { mongooseAssertionsPlugin } from './plugins/assertions';
8
+ import { mongooseLeanDecimal128ToStringPlugin } from './plugins/lean-decimal128-to-string';
12
9
  import { mongooseNormalizePlugin } from './plugins/normalize';
13
- import type { MongooseNormalizePluginOptions } from './plugins/normalize';
14
10
  import type { BaseMongoosePaginateModel } from './types';
15
11
  import type { BuildMongooseModelOptions } from './types/options';
16
12
 
@@ -27,8 +23,20 @@ export function buildMongooseModel<
27
23
  schema: Schema<DocType, Model, InstanceMethodsAndOverrides, QueryHelpers>,
28
24
  options?: BuildMongooseModelOptions,
29
25
  ): Model {
30
- if (options?.enableNormalizePlugin !== false) {
31
- registerMongooseNormalizePlugin(schema, options?.normalizePluginRecursive, options?.normalizePluginOptions);
26
+ const leanDecimal128ToStringPluginOptions = options?.plugins?.leanDecimal128ToString;
27
+ if (leanDecimal128ToStringPluginOptions !== false) {
28
+ schema.plugin(
29
+ mongooseLeanDecimal128ToStringPlugin,
30
+ typeof leanDecimal128ToStringPluginOptions === 'object' ? leanDecimal128ToStringPluginOptions : undefined,
31
+ );
32
+ }
33
+
34
+ const normalizePluginOptions = options?.plugins?.normalize;
35
+ if (normalizePluginOptions !== false) {
36
+ schema.plugin(
37
+ mongooseNormalizePlugin,
38
+ typeof normalizePluginOptions === 'object' ? normalizePluginOptions : undefined,
39
+ );
32
40
  }
33
41
 
34
42
  schema.plugin(mongooseAggregatePaginate);
@@ -36,28 +44,6 @@ export function buildMongooseModel<
36
44
  schema.plugin(mongoosePaginate);
37
45
  schema.set('timestamps', options?.timestamps ?? schema.get('timestamps') ?? true);
38
46
  customMongooseOptions.beforeModelBuild?.(schema);
39
- const connection =
40
- options?.connection
41
- || (
42
- mongooseConnections.default ||= mongoose.createConnection(
43
- process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017',
44
- )
45
- );
46
-
47
+ const connection = options?.connection ?? getDefaultMongooseConnection();
47
48
  return connection.model<DocType, Model, QueryHelpers>(name, schema, collection);
48
49
  }
49
- export function registerMongooseNormalizePlugin<
50
- DocType,
51
- Model extends MongooseModel<DocType, QueryHelpers, InstanceMethodsAndOverrides>,
52
- InstanceMethodsAndOverrides = object,
53
- QueryHelpers = object,
54
- >(
55
- schema: Schema<DocType, Model, InstanceMethodsAndOverrides, QueryHelpers>,
56
- recursive: boolean = true,
57
- options?: MongooseNormalizePluginOptions,
58
- ) {
59
- schema.plugin(mongooseNormalizePlugin, options);
60
- if (recursive) {
61
- schema.childSchemas.forEach(({ schema }) => registerMongooseNormalizePlugin(schema, recursive, options));
62
- }
63
- }
@@ -0,0 +1,14 @@
1
+ import mongoose from 'mongoose';
2
+ import type { Connection } from 'mongoose';
3
+
4
+ import {
5
+ customMongooseOptions,
6
+ mongooseConnectionState,
7
+ } from './_internals';
8
+
9
+ export function getDefaultMongooseConnection(): Connection {
10
+ return mongooseConnectionState.defaultConnection ||= mongoose.createConnection(
11
+ process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017',
12
+ customMongooseOptions.defaultConnectionOptions,
13
+ );
14
+ }
package/src/options.ts CHANGED
@@ -1,9 +1,16 @@
1
- import { customMongooseOptions } from './_internals';
1
+ import {
2
+ customMongooseOptions,
3
+ mongooseConnectionState,
4
+ } from './_internals';
2
5
  import type { CustomMongooseOptions } from './types/options';
3
6
 
4
7
  export function setCustomMongooseOptions<K extends keyof CustomMongooseOptions>(
5
8
  key: K,
6
9
  value: CustomMongooseOptions[K],
7
10
  ) {
11
+ if (key === 'defaultConnectionOptions' && mongooseConnectionState.defaultConnection) {
12
+ throw new Error('Default connection options must be set before the default connection is created.');
13
+ }
14
+
8
15
  customMongooseOptions[key] = value;
9
16
  }
@@ -0,0 +1,149 @@
1
+ import type {
2
+ Query,
3
+ Schema,
4
+ SchemaType,
5
+ } from 'mongoose';
6
+
7
+ declare module 'mongoose' {
8
+ interface LeanOptions {
9
+ /** Override conversion of marked Decimal128 fields. Defaults to the plugin's enabledByDefault setting. */
10
+ decimal128ToString?: boolean;
11
+ }
12
+ }
13
+
14
+ type QueryWithOptionalMap = Query<unknown, unknown> & { map?: (transform: (result: unknown) => unknown) => unknown };
15
+
16
+ export interface MongooseLeanDecimal128ToStringPluginOptions {
17
+ /** Whether marked fields are converted on lean queries by default. Defaults to true. */
18
+ enabledByDefault?: boolean;
19
+ }
20
+
21
+ // Constants/Variables
22
+ const registeredSchemas = new WeakSet<Schema>();
23
+
24
+ // Functions
25
+ const isNonNullObject = (value: unknown): value is Record<string, any> => value !== null && typeof value === 'object';
26
+
27
+ function convertDocument(schema: Schema, value: unknown) {
28
+ if (!isNonNullObject(value)) return;
29
+ const discriminatorKey = schema.get('discriminatorKey') ?? '__t';
30
+ const discriminatorSchema = Object.values(schema.discriminators ?? {}).find(
31
+ (childSchema) => childSchema.get('discriminatorKey') === discriminatorKey
32
+ && (childSchema as Schema & { discriminatorMapping?: { value: unknown } }).discriminatorMapping?.value
33
+ === value[discriminatorKey],
34
+ );
35
+
36
+ const documentSchema = discriminatorSchema ?? schema;
37
+ documentSchema.eachPath((path, schemaType) => {
38
+ // Maps are handled through their embedded schema type, not their synthetic $* path.
39
+ const pathSegments = path.split('.');
40
+ if (pathSegments.includes('$*')) return;
41
+ convertPath(value, pathSegments, schemaType);
42
+ });
43
+ }
44
+
45
+ function convertPath(value: unknown, pathSegments: string[], schemaType: SchemaType) {
46
+ if (Array.isArray(value)) {
47
+ value.forEach((item) => convertPath(item, pathSegments, schemaType));
48
+ return;
49
+ }
50
+
51
+ if (!isNonNullObject(value)) return;
52
+ const [key, ...remainingPathSegments] = pathSegments;
53
+ if (key === undefined || !Object.hasOwn(value, key)) return;
54
+ if (remainingPathSegments.length) convertPath(value[key], remainingPathSegments, schemaType);
55
+ else value[key] = convertValue(value[key], schemaType);
56
+ }
57
+
58
+ function convertValue(value: unknown, schemaType: SchemaType): unknown {
59
+ if (value === null || value === undefined) return value;
60
+ const embeddedSchemaType = schemaType.getEmbeddedSchemaType();
61
+ if (embeddedSchemaType && Array.isArray(value)) {
62
+ for (let i = 0; i < value.length; i++) {
63
+ if (Object.hasOwn(value, i)) value[i] = convertValue(value[i], embeddedSchemaType);
64
+ }
65
+
66
+ return value;
67
+ }
68
+
69
+ if (embeddedSchemaType && schemaType.instance === 'Map') {
70
+ if (value instanceof Map) value.forEach((item, key) => value.set(key, convertValue(item, embeddedSchemaType)));
71
+ else if (isNonNullObject(value)) {
72
+ for (const key of Object.keys(value)) value[key] = convertValue(value[key], embeddedSchemaType);
73
+ }
74
+
75
+ return value;
76
+ }
77
+
78
+ if (schemaType.schema) {
79
+ convertDocument(schemaType.schema, value);
80
+ return value;
81
+ }
82
+
83
+ if (
84
+ schemaType.instance === 'Decimal128'
85
+ && schemaType.options.leanDecimal128ToString === true
86
+ && isNonNullObject(value)
87
+ && value._bsontype === 'Decimal128'
88
+ && typeof value.toString === 'function'
89
+ ) return value.toString();
90
+
91
+ return value;
92
+ }
93
+
94
+ /**
95
+ * Converts marked Decimal128 fields to strings on lean queries without invoking getters.
96
+ *
97
+ * @remarks
98
+ * `decimal128().setToStringGetter` sets the `leanDecimal128ToString` schema-path option.
99
+ * Query-level `lean({ decimal128ToString: false })` disables this plugin only, not other plugins.
100
+ * Existing strings and nullish values are preserved. Missing/projected-out fields are not added.
101
+ * Supports nested schemas, arrays and maps. Aggregate results are intentionally not transformed.
102
+ * Registration is idempotent; the first registration's default options take precedence.
103
+ * Runtime conversion does not override Mongoose's inferred lean result types.
104
+ */
105
+ export function mongooseLeanDecimal128ToStringPlugin(
106
+ schema: Schema,
107
+ pluginOptions?: MongooseLeanDecimal128ToStringPluginOptions,
108
+ ) {
109
+ if (registeredSchemas.has(schema)) return;
110
+ registeredSchemas.add(schema);
111
+
112
+ function convertResult(query: QueryWithOptionalMap, result: unknown) {
113
+ const leanOptions = query.mongooseOptions().lean;
114
+ if (!leanOptions) return result;
115
+ const conversionEnabled = typeof leanOptions === 'object'
116
+ ? leanOptions.decimal128ToString ?? pluginOptions?.enabledByDefault ?? true
117
+ : pluginOptions?.enabledByDefault ?? true;
118
+
119
+ if (!conversionEnabled) return result;
120
+ const document = query.getOptions().includeResultMetadata && isNonNullObject(result) ? result.value : result;
121
+ const querySchema = query.model.schema;
122
+ if (Array.isArray(document)) document.forEach((value) => convertDocument(querySchema, value));
123
+ else convertDocument(querySchema, document);
124
+ return result;
125
+ }
126
+
127
+ // Find cursors do not run post('find'); match Mongoose's query/cursor transform surfaces.
128
+ schema.pre(
129
+ 'find',
130
+ function (this: QueryWithOptionalMap) {
131
+ const transform = (result: unknown) => convertResult(this, result);
132
+ if (typeof this.map === 'function') this.map(transform);
133
+ else if (typeof this.transform === 'function') this.transform(transform);
134
+ else this.setOptions({ transform });
135
+ },
136
+ );
137
+
138
+ schema.post(
139
+ [
140
+ 'findOne',
141
+ 'findOneAndUpdate',
142
+ 'findOneAndDelete',
143
+ 'findOneAndReplace',
144
+ ],
145
+ function (this: QueryWithOptionalMap, result: unknown) {
146
+ convertResult(this, result);
147
+ },
148
+ );
149
+ }
@@ -8,39 +8,58 @@ import type { Schema } from 'mongoose';
8
8
 
9
9
  export interface MongooseNormalizePluginOptions {
10
10
  /**
11
- * Whether to convert `_id` field to `id`.
12
- * If true, the `_id` field will be replaced with `id`.
11
+ * Whether to move the serialized `_id` value to `id`.
13
12
  *
14
- * @default true
13
+ * @remarks
14
+ * If `false`, preserves the value under `_id` instead. Only values other than `undefined` are copied.
15
+ *
16
+ * @defaultValue `true`.
15
17
  */
16
18
  convertIdField?: boolean;
17
19
 
20
+ /** Register normalization on child schemas too. Defaults to true. */
21
+ recursive?: boolean;
22
+
18
23
  /**
19
- * Whether to convert the `_id` field to a hex string if it's an ObjectId.
24
+ * Whether to convert a serialized `ObjectId` identifier to its hexadecimal string.
20
25
  *
21
- * @default true
26
+ * @remarks
27
+ * Applies before choosing the `id` or `_id` output key. Identifiers of other types are unchanged.
28
+ *
29
+ * @defaultValue `true`.
22
30
  */
23
31
  toHexIdIfObjectId?: boolean;
24
32
  }
25
33
 
34
+ // Constants/Variables
35
+ const registeredSchemas = new WeakSet<Schema>();
36
+
37
+ // Functions
38
+
26
39
  /**
27
- * Mongoose plugin to normalize the JSON output of documents.
40
+ * Registers JSON normalization on a Mongoose schema.
28
41
  *
29
- * This plugin modifies the `toJSON` method of Mongoose schemas to:
30
- * - Add an `id` field equal to the string representation of `_id`
31
- * - Remove the `_id` field
32
- * - Exclude fields marked as `private` from the JSON output
33
- * - Convert `Decimal128` fields to strings
34
- * - Remove the `__v` version key
42
+ * @remarks
43
+ * Mutates the schema's `toJSON` configuration while preserving its other options. The transform removes `__v`,
44
+ * normalizes `_id` according to the plugin options, removes schema paths marked `private`, and converts
45
+ * truthy serialized values at registered `Decimal128` paths to strings.
35
46
  *
36
- * @template S - The type of the schema.
47
+ * If an existing transform is a function, invokes it after normalization. If it returns `undefined`,
48
+ * preserves the normalized output and any mutations made by that transform; otherwise, uses its return value.
49
+ * That transform can change the normalized output, and its errors propagate during serialization.
50
+ * Registers itself on child schemas unless `recursive` is false. Does not configure `toObject`.
51
+ * Registration is idempotent per schema; the first registration's options take precedence.
37
52
  *
38
- * @param schema - The Mongoose schema to apply the plugin to.
53
+ * @param schema - The schema whose JSON serialization configuration is modified.
54
+ * @param pluginOptions - The normalization and registration options; omitted options use their documented defaults.
39
55
  */
40
56
  export function mongooseNormalizePlugin<S extends Schema>(
41
57
  schema: S,
42
58
  pluginOptions?: MongooseNormalizePluginOptions,
43
59
  ) {
60
+ if (registeredSchemas.has(schema)) return;
61
+ registeredSchemas.add(schema);
62
+
44
63
  // Collect special paths (Decimal128 & private)
45
64
  const decimalPaths: string[] = [];
46
65
  const privatePaths: string[] = [];
@@ -87,7 +106,8 @@ export function mongooseNormalizePlugin<S extends Schema>(
87
106
 
88
107
  // Run original toJSON transform
89
108
  if (toJsonTransform && typeof toJsonTransform !== 'boolean') {
90
- return toJsonTransform(doc as any, copiedRet as any, options as any);
109
+ const transformed = toJsonTransform(doc as any, copiedRet as any, options as any);
110
+ return transformed === undefined ? copiedRet : transformed;
91
111
  }
92
112
 
93
113
  // Return normalized object
@@ -95,4 +115,8 @@ export function mongooseNormalizePlugin<S extends Schema>(
95
115
  },
96
116
  },
97
117
  );
118
+
119
+ if (pluginOptions?.recursive !== false) {
120
+ schema.childSchemas.forEach(({ schema: child }) => child.plugin(mongooseNormalizePlugin, pluginOptions));
121
+ }
98
122
  }
@@ -5,7 +5,12 @@ type BaseSchemaType =
5
5
  | DateConstructor
6
6
  | NumberConstructor
7
7
  | Schema.Types.ObjectId['constructor']
8
- | StringConstructor;
8
+ | StringConstructor
9
+ | typeof Schema.Types.BigInt
10
+ | typeof Schema.Types.Double
11
+ | typeof Schema.Types.Int32
12
+ | typeof Schema.Types.Mixed
13
+ | typeof Schema.Types.UUID;
9
14
 
10
15
  // Constants/Variables
11
16
  const isFunctionKeys = new Set([
@@ -0,0 +1,190 @@
1
+ import { Schema } from 'mongoose';
2
+ import type {
3
+ DefaultType,
4
+ IndexDirection,
5
+ IndexOptions,
6
+ } from 'mongoose';
7
+ import type { Merge } from 'type-fest';
8
+
9
+ import type { Readonlyable } from '../types/_internals';
10
+
11
+ import { createBaseSchemaBuilderFactory } from './base';
12
+
13
+ type BigIntLimit = bigint;
14
+ type ExtendSchemaBuilder<
15
+ Props extends BaseProps,
16
+ ExtraOmitFields extends string,
17
+ > = Omit<
18
+ BigIntSchemaBuilder<Props, ExtraOmitFields>,
19
+ ExtraOmitFields | keyof Props
20
+ >;
21
+
22
+ interface BaseProps {
23
+ type: typeof Schema.Types.BigInt;
24
+ }
25
+
26
+ interface BigIntEnumValidator {
27
+ enumValues: (bigint | null)[];
28
+ message: string;
29
+ type: 'enum';
30
+ validator: (value: bigint | null | undefined) => boolean;
31
+ }
32
+
33
+ interface BigIntLimitValidator {
34
+ max?: bigint;
35
+ message: string;
36
+ min?: bigint;
37
+ type: 'max' | 'min';
38
+ validator: (value: bigint | null | undefined) => boolean;
39
+ }
40
+
41
+ export interface BigIntSchemaBuilder<Props extends BaseProps = BaseProps, ExtraOmitFields extends string = never> {
42
+ default: <
43
+ T extends ((this: any, doc: any) => DefaultType<D> | null | undefined) | DefaultType<D> | null | undefined,
44
+ D extends bigint,
45
+ >(value: T) => ExtendSchemaBuilder<
46
+ Merge<Props, { default: T }>,
47
+ ExtraOmitFields
48
+ >;
49
+
50
+ enum: <
51
+ T extends
52
+ | Readonlyable<(N | null)[]>
53
+ | { [path: string]: N | null }
54
+ | { message?: M; values: Readonlyable<(N | null)[]> },
55
+ M extends string,
56
+ N extends bigint,
57
+ >(value: T) => ExtendSchemaBuilder<
58
+ Merge<Props, BigIntValidationSchema>,
59
+ 'enum' | ExtraOmitFields
60
+ >;
61
+
62
+ immutable: ExtendSchemaBuilder<Merge<Props, { immutable: true }>, ExtraOmitFields>;
63
+ index: <T extends boolean | IndexDirection | IndexOptions>(value: T) => ExtendSchemaBuilder<
64
+ Merge<Props, { index: T }>,
65
+ ExtraOmitFields
66
+ >;
67
+
68
+ max: <
69
+ T extends L | Readonlyable<[L, S]>,
70
+ L extends BigIntLimit,
71
+ S extends string,
72
+ >(value: T) => ExtendSchemaBuilder<
73
+ Merge<Props, BigIntValidationSchema>,
74
+ 'max' | ExtraOmitFields
75
+ >;
76
+
77
+ min: <
78
+ T extends L | Readonlyable<[L, S]>,
79
+ L extends BigIntLimit,
80
+ S extends string,
81
+ >(value: T) => ExtendSchemaBuilder<
82
+ Merge<Props, BigIntValidationSchema>,
83
+ 'min' | ExtraOmitFields
84
+ >;
85
+
86
+ nonRequired: Props;
87
+ private: ExtendSchemaBuilder<Merge<Props, { private: true }>, ExtraOmitFields>;
88
+ required: Merge<Props, { required: true }>;
89
+ sparse: ExtendSchemaBuilder<Merge<Props, { sparse: true }>, ExtraOmitFields>;
90
+ unique: ExtendSchemaBuilder<Merge<Props, { unique: true }>, ExtraOmitFields>;
91
+ }
92
+
93
+ interface BigIntValidationSchema {
94
+ validate: (BigIntEnumValidator | BigIntLimitValidator)[];
95
+ }
96
+
97
+ // Constants/Variables
98
+ const defaultEnumValidateMessage = 'Path `{PATH}` ({VALUE}) is not a valid enum value.';
99
+ const defaultMinValidateMessage = 'Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).';
100
+ const defaultMaxValidateMessage = 'Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).';
101
+
102
+ // Functions
103
+ const baseBuilderFactory = createBaseSchemaBuilderFactory(Schema.Types.BigInt);
104
+
105
+ export function bigintSchemaBuilder() {
106
+ const schema: Record<string, any> = {};
107
+ const baseBuilder = baseBuilderFactory(schema);
108
+ return new Proxy(
109
+ baseBuilder,
110
+ {
111
+ get(target, key, receiver) {
112
+ if (key === 'enum') {
113
+ if (schema.validate?.some(({ type }: { type: string }) => type === 'enum')) {
114
+ throw new Error('Duplicate schema attribute: enum');
115
+ }
116
+
117
+ return (
118
+ value: Readonlyable<(bigint | null)[]>
119
+ | { [path: string]: bigint | null }
120
+ | { message?: string; values: Readonlyable<(bigint | null)[]> },
121
+ ) => {
122
+ let enumValues: (bigint | null)[];
123
+ let message: string | undefined;
124
+
125
+ if (Array.isArray(value)) enumValues = [...value];
126
+ else if ('values' in value && Array.isArray(value.values)) {
127
+ enumValues = [...value.values];
128
+ if ('message' in value && typeof value.message === 'string') message = value.message;
129
+ } else enumValues = Object.values(value);
130
+
131
+ const allowedValues = new Set(enumValues);
132
+ const validator: BigIntEnumValidator = {
133
+ enumValues,
134
+ message: message ?? defaultEnumValidateMessage,
135
+ type: 'enum',
136
+ validator: (value) => value === null || value === undefined || allowedValues.has(value),
137
+ };
138
+
139
+ schema.validate = [
140
+ ...schema.validate ?? [],
141
+ validator,
142
+ ];
143
+
144
+ return receiver;
145
+ };
146
+ }
147
+
148
+ if (key === 'max' || key === 'min') {
149
+ return (value: BigIntLimit | Readonlyable<[BigIntLimit, string]>) => {
150
+ const validator = createLimitValidator(key, value);
151
+ const validators = Array.isArray(schema.validate) ? schema.validate : [];
152
+ schema.validate = [
153
+ ...validators.filter(({ type }) => type !== key),
154
+ validator,
155
+ ];
156
+
157
+ return receiver;
158
+ };
159
+ }
160
+
161
+ return Reflect.get(target, key, receiver);
162
+ },
163
+ },
164
+ ) as BigIntSchemaBuilder;
165
+ }
166
+
167
+ function createLimitValidator(
168
+ type: 'max' | 'min',
169
+ value: BigIntLimit | Readonlyable<[BigIntLimit, string]>,
170
+ ): BigIntLimitValidator {
171
+ const [limit, message] = Array.isArray(value)
172
+ ? value as Readonly<[BigIntLimit, string]>
173
+ : [
174
+ value as BigIntLimit,
175
+ undefined,
176
+ ];
177
+
178
+ if (typeof limit !== 'bigint') throw new TypeError(`BigInt ${type} limit must be a bigint`);
179
+
180
+ return {
181
+ message: message ?? (type === 'min' ? defaultMinValidateMessage : defaultMaxValidateMessage),
182
+ [type]: limit,
183
+ type,
184
+ validator: (value) => {
185
+ if (value === null || value === undefined) return true;
186
+
187
+ return type === 'min' ? value >= limit : value <= limit;
188
+ },
189
+ };
190
+ }
@@ -20,10 +20,7 @@ interface BaseProps {
20
20
  type: BooleanSchemaDefinition;
21
21
  }
22
22
 
23
- export interface BooleanSchemaBuilder<
24
- Props extends BaseProps = BaseProps,
25
- ExtraOmitFields extends string = never,
26
- > {
23
+ export interface BooleanSchemaBuilder<Props extends BaseProps = BaseProps, ExtraOmitFields extends string = never> {
27
24
  default: <
28
25
  T extends ((this: any, doc: any) => DefaultType<D>) | DefaultType<D> | null,
29
26
  D extends boolean,
@@ -36,9 +36,9 @@ export interface DateSchemaBuilder<
36
36
 
37
37
  enum: <
38
38
  T extends
39
- | Readonlyable<Array<D | null>>
39
+ | Readonlyable<(D | null)[]>
40
40
  | { [path: string]: D | null }
41
- | { message?: M; values: Readonlyable<Array<D | null>> },
41
+ | { message?: M; values: Readonlyable<(D | null)[]> },
42
42
  D extends NativeDate,
43
43
  M extends string,
44
44
  >(value: T) => ExtendSchemaBuilder<
@@ -47,9 +47,9 @@ export interface Decimal128SchemaBuilder<
47
47
 
48
48
  enum: <
49
49
  T extends
50
- | Readonlyable<Array<D | null>>
50
+ | Readonlyable<(D | null)[]>
51
51
  | { [path: string]: D | null }
52
- | { message?: M; values: Readonlyable<Array<D | null>> },
52
+ | { message?: M; values: Readonlyable<(D | null)[]> },
53
53
  D extends Types.Decimal128,
54
54
  M extends string,
55
55
  >(value: T) => ExtendSchemaBuilder<
@@ -86,14 +86,18 @@ export interface Decimal128SchemaBuilder<
86
86
  required: Merge<Props, { required: true }>;
87
87
 
88
88
  /**
89
- * Sets the rounding and toFixed behavior for Decimal128 fields.
90
- * This method allows specifying the number of decimal places and the rounding strategy to be used when
91
- * saving the field to the database.
89
+ * Configures a setter that rounds decimal values and formats them with a fixed number of decimal places.
92
90
  *
93
- * @param places - The number of decimal places to round to (default is 2).
94
- * @param rounding - The rounding strategy from the Decimal.js library (default is Decimal.ROUND_DOWN).
91
+ * @remarks
92
+ * Replaces the configured setter on this builder. The setter converts non-nullish values through Decimal.js
93
+ * and returns a decimal string for Mongoose to cast to `Decimal128`. It returns `undefined` for `null` or
94
+ * `undefined`. Decimal.js validates conversion and formatting when the setter processes a value,
95
+ * not when the setter is configured.
95
96
  *
96
- * @returns A schema builder with the rounding and toFixed behavior applied to the `set` option in Mongoose.
97
+ * @param places - The non-negative integer number of decimal places. Defaults to `2`.
98
+ * @param rounding - The Decimal.js rounding mode. Defaults to `Decimal.ROUND_DOWN`, which rounds toward zero.
99
+ *
100
+ * @returns This instance for chaining.
97
101
  */
98
102
  setRoundAndToFixedSetter: (places?: number, rounding?: Decimal.Rounding) => ExtendSchemaBuilder<
99
103
  Merge<Props, ToStringSetterSchema>,
@@ -101,13 +105,14 @@ export interface Decimal128SchemaBuilder<
101
105
  >;
102
106
 
103
107
  /**
104
- * Sets the toString behavior for Decimal128 fields.
105
- * This method defines how the Decimal128 field should be converted to a string when processing or
106
- * retrieving the value in the application (e.g., via getters), while still storing the value as Decimal128
107
- * in the database.
108
+ * Configures a getter that converts decimal values to strings.
109
+ *
110
+ * @remarks
111
+ * Replaces the configured getter on this builder. The getter returns the value's string representation,
112
+ * or `undefined` for `null` or `undefined`. It changes the read representation, not the stored BSON type.
113
+ * Marks this path for the lean Decimal128-to-string plugin; the plugin does not invoke this getter.
108
114
  *
109
- * @returns A schema builder with the custom `get` behavior applied to convert the Decimal128 field to a string
110
- * when accessed in the application.
115
+ * @returns This instance for chaining.
111
116
  */
112
117
  setToStringGetter: ExtendSchemaBuilder<Merge<Props, ToStringGetterSchema>, 'setToStringGetter' | ExtraOmitFields>;
113
118
  sparse: ExtendSchemaBuilder<Merge<Props, { sparse: true }>, ExtraOmitFields>;
@@ -120,6 +125,7 @@ interface Decimal128ValidationSchema {
120
125
 
121
126
  interface ToStringGetterSchema {
122
127
  get: (value?: Types.Decimal128) => string | undefined;
128
+ leanDecimal128ToString: true;
123
129
  }
124
130
 
125
131
  interface ToStringSetterSchema {
@@ -195,6 +201,7 @@ export function decimal128SchemaBuilder() {
195
201
 
196
202
  if (key === 'setToStringGetter') {
197
203
  schema.get = (value?: Types.Decimal128) => value?.toString();
204
+ schema.leanDecimal128ToString = true;
198
205
  return receiver;
199
206
  }
200
207