@kikiutils/mongoose 3.3.0 → 4.0.1

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.
package/README.md CHANGED
@@ -24,7 +24,7 @@ A Mongoose plugin for enhanced JSON normalization and common schema creation, wi
24
24
  ## Requirements
25
25
 
26
26
  - **Mongoose** `>= 8`
27
- - **Node.js** `>= 18.12.1`
27
+ - **Node.js** `>= 20.0.0`
28
28
 
29
29
  ## Installation
30
30
 
@@ -37,10 +37,12 @@ function mongooseNormalizePlugin(schema, pluginOptions) {
37
37
  if (pluginOptions?.toHexIdIfObjectId !== false) {
38
38
  _id = _id instanceof mongoose.Types.ObjectId ? _id.toHexString() : _id;
39
39
  }
40
- if (pluginOptions?.convertIdField !== false)
41
- copiedRet.id = _id;
42
- else
43
- copiedRet._id = _id;
40
+ if (_id !== undefined) {
41
+ if (pluginOptions?.convertIdField !== false)
42
+ copiedRet.id = _id;
43
+ else
44
+ copiedRet._id = _id;
45
+ }
44
46
  for (const path in schema.paths) {
45
47
  if (schema.paths[path]?.options?.private)
46
48
  lodashUnset__default(copiedRet, path);
@@ -1 +1 @@
1
- {"version":3,"file":"normalize.cjs","sources":["../../src/plugins/normalize.ts"],"sourcesContent":["// @ts-expect-error Ignore this error.\nimport lodashGet from 'lodash/get.js';\n// @ts-expect-error Ignore this error.\nimport lodashSet from 'lodash/set.js';\n// @ts-expect-error Ignore this error.\nimport lodashUnset from 'lodash/unset.js';\nimport { Types } from 'mongoose';\nimport type { Schema } from 'mongoose';\n\nexport interface MongooseNormalizePluginOptions {\n /**\n * Whether to convert `_id` field to `id`.\n * If true, the `_id` field will be replaced with `id`.\n *\n * @default true\n */\n convertIdField?: boolean;\n\n /**\n * Whether to convert the `_id` field to a hex string if it's an ObjectId.\n *\n * @default true\n */\n toHexIdIfObjectId?: boolean;\n}\n\n/**\n * Mongoose plugin to normalize the JSON output of documents.\n *\n * This plugin modifies the `toJSON` method of Mongoose schemas to:\n * - Add an `id` field equal to the string representation of `_id`\n * - Remove the `_id` field\n * - Exclude fields marked as `private` from the JSON output\n * - Convert `Decimal128` fields to strings\n * - Remove the `__v` version key\n *\n * @template S - The type of the schema.\n *\n * @param schema - The Mongoose schema to apply the plugin to.\n */\nexport function mongooseNormalizePlugin<S extends Schema>(schema: S, pluginOptions?: MongooseNormalizePluginOptions) {\n const toJson = schema.get('toJSON');\n const toJsonTransform = toJson?.transform;\n schema.set(\n 'toJSON',\n {\n ...toJson,\n transform(doc, ret, options) {\n // eslint-disable-next-line style/object-curly-newline\n let { __v, _id, ...copiedRet } = ret;\n if (pluginOptions?.toHexIdIfObjectId !== false) {\n _id = _id instanceof Types.ObjectId ? _id.toHexString() : _id;\n }\n\n if (pluginOptions?.convertIdField !== false) copiedRet.id = _id;\n else copiedRet._id = _id;\n for (const path in schema.paths) {\n if (schema.paths[path]?.options?.private) lodashUnset(copiedRet, path);\n if (schema.paths[path]?.instance === 'Decimal128') {\n const value: Types.Decimal128 | undefined = lodashGet(copiedRet, path);\n if (value) lodashSet(copiedRet, path, value.toString());\n }\n }\n\n if (toJsonTransform && typeof toJsonTransform !== 'boolean') {\n return toJsonTransform(doc as any, copiedRet as any, options as any);\n }\n\n return copiedRet;\n },\n },\n );\n}\n"],"names":["Types","lodashUnset","lodashGet","lodashSet"],"mappings":";;;;;;;;;;;;;AAAA;AA0BA;;;;;;;;;;;;;AAaG;AACG,SAAU,uBAAuB,CAAmB,MAAS,EAAE,aAA8C,EAAA;IAC/G,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;AACnC,IAAA,MAAM,eAAe,GAAG,MAAM,EAAE,SAAS;AACzC,IAAA,MAAM,CAAC,GAAG,CACN,QAAQ,EACR;AACI,QAAA,GAAG,MAAM;AACT,QAAA,SAAS,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,EAAA;;YAEvB,IAAI,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,SAAS,EAAE,GAAG,GAAG;AACpC,YAAA,IAAI,aAAa,EAAE,iBAAiB,KAAK,KAAK,EAAE;AAC5C,gBAAA,GAAG,GAAG,GAAG,YAAYA,cAAK,CAAC,QAAQ,GAAG,GAAG,CAAC,WAAW,EAAE,GAAG,GAAG;YACjE;AAEA,YAAA,IAAI,aAAa,EAAE,cAAc,KAAK,KAAK;AAAE,gBAAA,SAAS,CAAC,EAAE,GAAG,GAAG;;AAC1D,gBAAA,SAAS,CAAC,GAAG,GAAG,GAAG;AACxB,YAAA,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,KAAK,EAAE;gBAC7B,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,OAAO;AAAE,oBAAAC,oBAAW,CAAC,SAAS,EAAE,IAAI,CAAC;gBACtE,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,QAAQ,KAAK,YAAY,EAAE;oBAC/C,MAAM,KAAK,GAAiCC,kBAAS,CAAC,SAAS,EAAE,IAAI,CAAC;AACtE,oBAAA,IAAI,KAAK;wBAAEC,kBAAS,CAAC,SAAS,EAAE,IAAI,EAAE,KAAK,CAAC,QAAQ,EAAE,CAAC;gBAC3D;YACJ;AAEA,YAAA,IAAI,eAAe,IAAI,OAAO,eAAe,KAAK,SAAS,EAAE;gBACzD,OAAO,eAAe,CAAC,GAAU,EAAE,SAAgB,EAAE,OAAc,CAAC;YACxE;AAEA,YAAA,OAAO,SAAS;QACpB,CAAC;AACJ,KAAA,CACJ;AACL;;;;"}
1
+ {"version":3,"file":"normalize.cjs","sources":["../../src/plugins/normalize.ts"],"sourcesContent":["// @ts-expect-error Ignore this error.\nimport lodashGet from 'lodash/get.js';\n// @ts-expect-error Ignore this error.\nimport lodashSet from 'lodash/set.js';\n// @ts-expect-error Ignore this error.\nimport lodashUnset from 'lodash/unset.js';\nimport { Types } from 'mongoose';\nimport type { Schema } from 'mongoose';\n\nexport interface MongooseNormalizePluginOptions {\n /**\n * Whether to convert `_id` field to `id`.\n * If true, the `_id` field will be replaced with `id`.\n *\n * @default true\n */\n convertIdField?: boolean;\n\n /**\n * Whether to convert the `_id` field to a hex string if it's an ObjectId.\n *\n * @default true\n */\n toHexIdIfObjectId?: boolean;\n}\n\n/**\n * Mongoose plugin to normalize the JSON output of documents.\n *\n * This plugin modifies the `toJSON` method of Mongoose schemas to:\n * - Add an `id` field equal to the string representation of `_id`\n * - Remove the `_id` field\n * - Exclude fields marked as `private` from the JSON output\n * - Convert `Decimal128` fields to strings\n * - Remove the `__v` version key\n *\n * @template S - The type of the schema.\n *\n * @param schema - The Mongoose schema to apply the plugin to.\n */\nexport function mongooseNormalizePlugin<S extends Schema>(schema: S, pluginOptions?: MongooseNormalizePluginOptions) {\n const toJson = schema.get('toJSON');\n const toJsonTransform = toJson?.transform;\n schema.set(\n 'toJSON',\n {\n ...toJson,\n transform(doc, ret, options) {\n // eslint-disable-next-line style/object-curly-newline\n let { __v, _id, ...copiedRet } = ret;\n if (pluginOptions?.toHexIdIfObjectId !== false) {\n _id = _id instanceof Types.ObjectId ? _id.toHexString() : _id;\n }\n\n if (_id !== undefined) {\n if (pluginOptions?.convertIdField !== false) copiedRet.id = _id;\n else copiedRet._id = _id;\n }\n\n for (const path in schema.paths) {\n if (schema.paths[path]?.options?.private) lodashUnset(copiedRet, path);\n if (schema.paths[path]?.instance === 'Decimal128') {\n const value: Types.Decimal128 | undefined = lodashGet(copiedRet, path);\n if (value) lodashSet(copiedRet, path, value.toString());\n }\n }\n\n if (toJsonTransform && typeof toJsonTransform !== 'boolean') {\n return toJsonTransform(doc as any, copiedRet as any, options as any);\n }\n\n return copiedRet;\n },\n },\n );\n}\n"],"names":["Types","lodashUnset","lodashGet","lodashSet"],"mappings":";;;;;;;;;;;;;AAAA;AA0BA;;;;;;;;;;;;;AAaG;AACG,SAAU,uBAAuB,CAAmB,MAAS,EAAE,aAA8C,EAAA;IAC/G,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,QA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,KAAA,CACJ;AACL;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"normalize.d.ts","sourceRoot":"","sources":["../../src/plugins/normalize.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAEvC,MAAM,WAAW,8BAA8B;IAC3C;;;;;OAKG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;IAEzB;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC/B;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,uBAAuB,CAAC,CAAC,SAAS,MAAM,EAAE,MAAM,EAAE,CAAC,EAAE,aAAa,CAAC,EAAE,8BAA8B,QAgClH"}
1
+ {"version":3,"file":"normalize.d.ts","sourceRoot":"","sources":["../../src/plugins/normalize.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAEvC,MAAM,WAAW,8BAA8B;IAC3C;;;;;OAKG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;IAEzB;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC/B;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,uBAAuB,CAAC,CAAC,SAAS,MAAM,EAAE,MAAM,EAAE,CAAC,EAAE,aAAa,CAAC,EAAE,8BAA8B,QAmClH"}
@@ -29,10 +29,12 @@ function mongooseNormalizePlugin(schema, pluginOptions) {
29
29
  if (pluginOptions?.toHexIdIfObjectId !== false) {
30
30
  _id = _id instanceof Types.ObjectId ? _id.toHexString() : _id;
31
31
  }
32
- if (pluginOptions?.convertIdField !== false)
33
- copiedRet.id = _id;
34
- else
35
- copiedRet._id = _id;
32
+ if (_id !== undefined) {
33
+ if (pluginOptions?.convertIdField !== false)
34
+ copiedRet.id = _id;
35
+ else
36
+ copiedRet._id = _id;
37
+ }
36
38
  for (const path in schema.paths) {
37
39
  if (schema.paths[path]?.options?.private)
38
40
  lodashUnset(copiedRet, path);
@@ -1 +1 @@
1
- {"version":3,"file":"normalize.mjs","sources":["../../src/plugins/normalize.ts"],"sourcesContent":["// @ts-expect-error Ignore this error.\nimport lodashGet from 'lodash/get.js';\n// @ts-expect-error Ignore this error.\nimport lodashSet from 'lodash/set.js';\n// @ts-expect-error Ignore this error.\nimport lodashUnset from 'lodash/unset.js';\nimport { Types } from 'mongoose';\nimport type { Schema } from 'mongoose';\n\nexport interface MongooseNormalizePluginOptions {\n /**\n * Whether to convert `_id` field to `id`.\n * If true, the `_id` field will be replaced with `id`.\n *\n * @default true\n */\n convertIdField?: boolean;\n\n /**\n * Whether to convert the `_id` field to a hex string if it's an ObjectId.\n *\n * @default true\n */\n toHexIdIfObjectId?: boolean;\n}\n\n/**\n * Mongoose plugin to normalize the JSON output of documents.\n *\n * This plugin modifies the `toJSON` method of Mongoose schemas to:\n * - Add an `id` field equal to the string representation of `_id`\n * - Remove the `_id` field\n * - Exclude fields marked as `private` from the JSON output\n * - Convert `Decimal128` fields to strings\n * - Remove the `__v` version key\n *\n * @template S - The type of the schema.\n *\n * @param schema - The Mongoose schema to apply the plugin to.\n */\nexport function mongooseNormalizePlugin<S extends Schema>(schema: S, pluginOptions?: MongooseNormalizePluginOptions) {\n const toJson = schema.get('toJSON');\n const toJsonTransform = toJson?.transform;\n schema.set(\n 'toJSON',\n {\n ...toJson,\n transform(doc, ret, options) {\n // eslint-disable-next-line style/object-curly-newline\n let { __v, _id, ...copiedRet } = ret;\n if (pluginOptions?.toHexIdIfObjectId !== false) {\n _id = _id instanceof Types.ObjectId ? _id.toHexString() : _id;\n }\n\n if (pluginOptions?.convertIdField !== false) copiedRet.id = _id;\n else copiedRet._id = _id;\n for (const path in schema.paths) {\n if (schema.paths[path]?.options?.private) lodashUnset(copiedRet, path);\n if (schema.paths[path]?.instance === 'Decimal128') {\n const value: Types.Decimal128 | undefined = lodashGet(copiedRet, path);\n if (value) lodashSet(copiedRet, path, value.toString());\n }\n }\n\n if (toJsonTransform && typeof toJsonTransform !== 'boolean') {\n return toJsonTransform(doc as any, copiedRet as any, options as any);\n }\n\n return copiedRet;\n },\n },\n );\n}\n"],"names":[],"mappings":";;;;;AAAA;AA0BA;;;;;;;;;;;;;AAaG;AACG,SAAU,uBAAuB,CAAmB,MAAS,EAAE,aAA8C,EAAA;IAC/G,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;AACnC,IAAA,MAAM,eAAe,GAAG,MAAM,EAAE,SAAS;AACzC,IAAA,MAAM,CAAC,GAAG,CACN,QAAQ,EACR;AACI,QAAA,GAAG,MAAM;AACT,QAAA,SAAS,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,EAAA;;YAEvB,IAAI,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,SAAS,EAAE,GAAG,GAAG;AACpC,YAAA,IAAI,aAAa,EAAE,iBAAiB,KAAK,KAAK,EAAE;AAC5C,gBAAA,GAAG,GAAG,GAAG,YAAY,KAAK,CAAC,QAAQ,GAAG,GAAG,CAAC,WAAW,EAAE,GAAG,GAAG;YACjE;AAEA,YAAA,IAAI,aAAa,EAAE,cAAc,KAAK,KAAK;AAAE,gBAAA,SAAS,CAAC,EAAE,GAAG,GAAG;;AAC1D,gBAAA,SAAS,CAAC,GAAG,GAAG,GAAG;AACxB,YAAA,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,KAAK,EAAE;gBAC7B,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,OAAO;AAAE,oBAAA,WAAW,CAAC,SAAS,EAAE,IAAI,CAAC;gBACtE,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,QAAQ,KAAK,YAAY,EAAE;oBAC/C,MAAM,KAAK,GAAiC,SAAS,CAAC,SAAS,EAAE,IAAI,CAAC;AACtE,oBAAA,IAAI,KAAK;wBAAE,SAAS,CAAC,SAAS,EAAE,IAAI,EAAE,KAAK,CAAC,QAAQ,EAAE,CAAC;gBAC3D;YACJ;AAEA,YAAA,IAAI,eAAe,IAAI,OAAO,eAAe,KAAK,SAAS,EAAE;gBACzD,OAAO,eAAe,CAAC,GAAU,EAAE,SAAgB,EAAE,OAAc,CAAC;YACxE;AAEA,YAAA,OAAO,SAAS;QACpB,CAAC;AACJ,KAAA,CACJ;AACL;;;;"}
1
+ {"version":3,"file":"normalize.mjs","sources":["../../src/plugins/normalize.ts"],"sourcesContent":["// @ts-expect-error Ignore this error.\nimport lodashGet from 'lodash/get.js';\n// @ts-expect-error Ignore this error.\nimport lodashSet from 'lodash/set.js';\n// @ts-expect-error Ignore this error.\nimport lodashUnset from 'lodash/unset.js';\nimport { Types } from 'mongoose';\nimport type { Schema } from 'mongoose';\n\nexport interface MongooseNormalizePluginOptions {\n /**\n * Whether to convert `_id` field to `id`.\n * If true, the `_id` field will be replaced with `id`.\n *\n * @default true\n */\n convertIdField?: boolean;\n\n /**\n * Whether to convert the `_id` field to a hex string if it's an ObjectId.\n *\n * @default true\n */\n toHexIdIfObjectId?: boolean;\n}\n\n/**\n * Mongoose plugin to normalize the JSON output of documents.\n *\n * This plugin modifies the `toJSON` method of Mongoose schemas to:\n * - Add an `id` field equal to the string representation of `_id`\n * - Remove the `_id` field\n * - Exclude fields marked as `private` from the JSON output\n * - Convert `Decimal128` fields to strings\n * - Remove the `__v` version key\n *\n * @template S - The type of the schema.\n *\n * @param schema - The Mongoose schema to apply the plugin to.\n */\nexport function mongooseNormalizePlugin<S extends Schema>(schema: S, pluginOptions?: MongooseNormalizePluginOptions) {\n const toJson = schema.get('toJSON');\n const toJsonTransform = toJson?.transform;\n schema.set(\n 'toJSON',\n {\n ...toJson,\n transform(doc, ret, options) {\n // eslint-disable-next-line style/object-curly-newline\n let { __v, _id, ...copiedRet } = ret;\n if (pluginOptions?.toHexIdIfObjectId !== false) {\n _id = _id instanceof Types.ObjectId ? _id.toHexString() : _id;\n }\n\n if (_id !== undefined) {\n if (pluginOptions?.convertIdField !== false) copiedRet.id = _id;\n else copiedRet._id = _id;\n }\n\n for (const path in schema.paths) {\n if (schema.paths[path]?.options?.private) lodashUnset(copiedRet, path);\n if (schema.paths[path]?.instance === 'Decimal128') {\n const value: Types.Decimal128 | undefined = lodashGet(copiedRet, path);\n if (value) lodashSet(copiedRet, path, value.toString());\n }\n }\n\n if (toJsonTransform && typeof toJsonTransform !== 'boolean') {\n return toJsonTransform(doc as any, copiedRet as any, options as any);\n }\n\n return copiedRet;\n },\n },\n );\n}\n"],"names":[],"mappings":";;;;;AAAA;AA0BA;;;;;;;;;;;;;AAaG;AACG,SAAU,uBAAuB,CAAmB,MAAS,EAAE,aAA8C,EAAA;IAC/G,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;AACnC,IAAA,MAAM,eAAe,GAAG,MAAM,EAAE,SAAS;AACzC,IAAA,MAAM,CAAC,GAAG,CACN,QAAQ,EACR;AACI,QAAA,GAAG,MAAM;AACT,QAAA,SAAS,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,EAAA;;YAEvB,IAAI,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,SAAS,EAAE,GAAG,GAAG;AACpC,YAAA,IAAI,aAAa,EAAE,iBAAiB,KAAK,KAAK,EAAE;AAC5C,gBAAA,GAAG,GAAG,GAAG,YAAY,KAAK,CAAC,QAAQ,GAAG,GAAG,CAAC,WAAW,EAAE,GAAG,GAAG;YACjE;AAEA,YAAA,IAAI,GAAG,KAAK,SAAS,EAAE;AACnB,gBAAA,IAAI,aAAa,EAAE,cAAc,KAAK,KAAK;AAAE,oBAAA,SAAS,CAAC,EAAE,GAAG,GAAG;;AAC1D,oBAAA,SAAS,CAAC,GAAG,GAAG,GAAG;YAC5B;AAEA,YAAA,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,KAAK,EAAE;gBAC7B,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,OAAO;AAAE,oBAAA,WAAW,CAAC,SAAS,EAAE,IAAI,CAAC;gBACtE,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,QAAQ,KAAK,YAAY,EAAE;oBAC/C,MAAM,KAAK,GAAiC,SAAS,CAAC,SAAS,EAAE,IAAI,CAAC;AACtE,oBAAA,IAAI,KAAK;wBAAE,SAAS,CAAC,SAAS,EAAE,IAAI,EAAE,KAAK,CAAC,QAAQ,EAAE,CAAC;gBAC3D;YACJ;AAEA,YAAA,IAAI,eAAe,IAAI,OAAO,eAAe,KAAK,SAAS,EAAE;gBACzD,OAAO,eAAe,CAAC,GAAU,EAAE,SAAgB,EAAE,OAAc,CAAC;YACxE;AAEA,YAAA,OAAO,SAAS;QACpB,CAAC;AACJ,KAAA,CACJ;AACL;;;;"}
@@ -1,4 +1,3 @@
1
- import type { Types } from 'mongoose';
2
1
  import type { SetFieldType } from 'type-fest';
3
2
  import type { IfElse } from './utils';
4
3
  declare global {
@@ -15,7 +14,7 @@ declare global {
15
14
  }, unknown> & {
16
15
  id: string;
17
16
  };
18
- type DataToBaseMongooseDocType<T, ObjectIdFields extends keyof T = never, DateFields extends Exclude<keyof T, ObjectIdFields> = never, CreatedAtField extends boolean = true, UpdatedAtField extends boolean = true> = BaseMongooseDocType<SetFieldType<SetFieldType<T, DateFields, Date>, ObjectIdFields, Types.ObjectId>, CreatedAtField, UpdatedAtField>;
17
+ type DataToBaseMongooseDocType<T, ObjectIdFields extends keyof T = never, DateFields extends Exclude<keyof T, ObjectIdFields> = never, CreatedAtField extends boolean = true, UpdatedAtField extends boolean = true> = BaseMongooseDocType<SetFieldsToObjectId<SetFieldType<T, DateFields, Date>, ObjectIdFields>, CreatedAtField, UpdatedAtField>;
19
18
  /**
20
19
  * Type definition to omit timestamp fields (`createdAt`, `updatedAt`)
21
20
  * and other specified fields (`K`) from a given type `T`.
@@ -1 +1 @@
1
- {"version":3,"file":"data.d.ts","sourceRoot":"","sources":["../../src/types/data.ts"],"names":[],"mappings":"AAAA,OAAO,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,SAAS,MAAM,CAAC,IAAI,IAAI,CAAC,CAAC,EAAE,WAAW,GAAG,WAAW,GAAG,CAAC,CAAC,CAAC;IAE1G;;;;;;OAMG;IACH,KAAK,mCAAmC,CACpC,CAAC,EACD,CAAC,SAAS,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,KAAK,IAC1C,IAAI,CACJ,CAAC,EACD,WAAW,GAAG,WAAW,GAAG,CAAC,CAChC,CAAC;IAEF;;;;;OAKG;IACH,KAAK,+BAA+B,CAChC,SAAS,SAAS,OAAO,GAAG,IAAI,EAChC,SAAS,SAAS,OAAO,GAAG,IAAI,IAEhC,MAAM,CAAC,SAAS,EAAE;QAAE,SAAS,EAAE,MAAM,CAAA;KAAE,EAAE,MAAM,CAAC,GAChD,MAAM,CAAC,SAAS,EAAE;QAAE,SAAS,EAAE,MAAM,CAAA;KAAE,EAAE,MAAM,CAAC,CAAC;CACxD"}
@@ -75,6 +75,6 @@ declare global {
75
75
  * @template QueryHelpers - Optional type parameter for additional query helper methods.
76
76
  */
77
77
  type MongooseHydratedDocument<DocType, InstanceMethodsAndOverrides = object, QueryHelpers = object> = HydratedDocument<DocType, InstanceMethodsAndOverrides, QueryHelpers>;
78
- type SetFieldsToObjectId<T, F extends keyof T> = SetFieldType<T, F, Types.ObjectId>;
78
+ type SetFieldsToObjectId<T, K extends keyof T> = SetFieldType<T, K, Types.ObjectId>;
79
79
  }
80
80
  //# sourceMappingURL=index.d.ts.map
package/dist/utils.cjs CHANGED
@@ -98,8 +98,20 @@ async function mongooseDocumentOrObjectIdToDocument(documentOrObjectId, model, s
98
98
  }
99
99
  return documentOrObjectId;
100
100
  }
101
+ /**
102
+ * Converts the input, which can be a MongoDB ObjectId or a string,
103
+ * into a 24-character hexadecimal string representation of the ObjectId.
104
+ *
105
+ * @param {string | Types.ObjectId} id - The ObjectId instance or its string representation
106
+ *
107
+ * @returns {string} The hexadecimal string representation of the ObjectId
108
+ */
109
+ function toObjectIdHexString(id) {
110
+ return id instanceof mongoose.Types.ObjectId ? id.toHexString() : id;
111
+ }
101
112
 
102
113
  exports.assertMongooseUpdateSuccess = assertMongooseUpdateSuccess;
103
114
  exports.buildMongooseModel = buildMongooseModel;
104
115
  exports.mongooseDocumentOrObjectIdToDocument = mongooseDocumentOrObjectIdToDocument;
116
+ exports.toObjectIdHexString = toObjectIdHexString;
105
117
  //# sourceMappingURL=utils.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.cjs","sources":["../src/utils.ts"],"sourcesContent":["import mongoose, { Types } from 'mongoose';\nimport type {\n mongo,\n Schema,\n} from 'mongoose';\nimport mongooseAggregatePaginate from 'mongoose-aggregate-paginate-v2';\nimport mongoosePaginate from 'mongoose-paginate-v2';\n\nimport { customMongooseOptions } from './_internals';\nimport { mongooseConnections } from './constants';\nimport type { setCustomMongooseOptions } from './options';\nimport { mongooseNormalizePlugin } from './plugins/normalize';\nimport type { BuildMongooseModelOptions } from './types/options';\n\nexport type DoNotRemoveOrUseThisType = typeof setCustomMongooseOptions;\n\n/**\n * Asserts that a Mongoose update operation was successful by checking that it was acknowledged\n * and that at least the expected number of documents were modified.\n *\n * This function is intended for use with `updateOne`, `updateMany`, or any update operation\n * that returns a MongoDB `UpdateResult`.\n *\n * @template T - The shape of the document being updated.\n * @param updatePromise - A promise returned from a Mongoose update operation.\n * @param expectedModifiedCount - The minimum number of documents expected to be modified. Defaults to 1.\n * @throws Will throw an error if:\n * - The operation was not acknowledged by MongoDB,\n * - Fewer documents were modified than expected.\n */\nexport async function assertMongooseUpdateSuccess<T extends mongo.BSON.Document>(\n updatePromise: Promise<mongo.UpdateResult<T>>,\n expectedModifiedCount = 1,\n) {\n const updateResult = await updatePromise;\n if (!updateResult.acknowledged) throw new Error('Update was not acknowledged');\n if (updateResult.modifiedCount < expectedModifiedCount) {\n // eslint-disable-next-line style/max-len\n throw new Error(`Expected to modify at least ${expectedModifiedCount} document(s), but modified ${updateResult.modifiedCount}`);\n }\n}\n\n/**\n * Builds and returns a Mongoose model with specified schema and options.\n *\n * This function sets up a Mongoose model with optional plugins and timestamp settings.\n * It can optionally use a specified connection or the default connection.\n *\n * Determine the connection to use:\n * 1. Use the connection provided in the options, if available.\n * 2. Otherwise, use the default connection stored in `mongooseConnections`.\n * 3. If there's no default connection, create one using the MongoDB URI from the environment variables,\n * or fallback to a local MongoDB instance.\n *\n * You can set a function to be executed before the final build by using {@link setCustomMongooseOptions}.\n * However, ensure that this option is configured before calling {@link buildMongooseModel}.\n *\n * @template DocType - The type of the document.\n * @template Model - The type of the model, which extends `BaseMongoosePaginateModel`.\n * @template InstanceMethodsAndOverrides - The type for instance methods and overrides.\n * @template QueryHelpers - The type for additional query helpers.\n *\n * @param collection - The name of the collection.\n * @param name - The name of the model.\n * @param schema - The Mongoose schema to use for the model.\n * @param options - Optional settings for building the model.\n *\n * @returns The created Mongoose model.\n */\nexport function buildMongooseModel<\n DocType,\n Model extends BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n InstanceMethodsAndOverrides = object,\n QueryHelpers = object,\n>(\n collection: string,\n name: string,\n schema: Schema<DocType, Model, InstanceMethodsAndOverrides, QueryHelpers>,\n options?: BuildMongooseModelOptions,\n) {\n if (options?.enableNormalizePlugin !== false) {\n schema.plugin(mongooseNormalizePlugin, options?.normalizePluginOptions);\n }\n\n schema.plugin(mongooseAggregatePaginate);\n schema.plugin(mongoosePaginate);\n schema.set('timestamps', options?.timestamps ?? schema.get('timestamps') ?? true);\n customMongooseOptions.beforeModelBuild?.(schema);\n // eslint-disable-next-line style/max-len\n const connection = options?.connection || (mongooseConnections.default ||= mongoose.createConnection(process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017'));\n return connection.model<DocType, Model, QueryHelpers>(name, schema, collection);\n}\n\n/**\n * Converts a document or ObjectId to a document using the specified model.\n *\n * This function takes a document or ObjectId and returns the corresponding document\n * from the database using the specified model. Optionally, specific fields can be selected.\n *\n * @template D - The type of the hydrated document.\n * @template DocType - The type of the document.\n * @template InstanceMethodsAndOverrides - The type for instance methods and overrides.\n * @template QueryHelpers - The type for additional query helpers.\n *\n * @param documentOrObjectId - The document or ObjectId to convert.\n * @param model - The Mongoose model to use for the conversion.\n * @param selectFields - Optional fields to select from the document.\n *\n * @returns The corresponding document or null if not found.\n */\nexport async function mongooseDocumentOrObjectIdToDocument<\n D extends MongooseHydratedDocument<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n DocType,\n InstanceMethodsAndOverrides,\n QueryHelpers,\n>(\n documentOrObjectId: MongooseDocumentOrObjectId<D>,\n model: BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n selectFields?: string[],\n) {\n if (typeof documentOrObjectId === 'string' || documentOrObjectId instanceof Types.ObjectId) {\n return (await model.findById(documentOrObjectId).select(selectFields || [])) as D | null;\n }\n\n return documentOrObjectId;\n}\n"],"names":["mongooseNormalizePlugin","mongooseAggregatePaginate","mongoosePaginate","customMongooseOptions","mongooseConnections","mongoose","Types"],"mappings":";;;;;;;;;;;;;;;AAgBA;;;;;;;;;;;;;AAaG;AACI,eAAe,2BAA2B,CAC7C,aAA6C,EAC7C,qBAAqB,GAAG,CAAC,EAAA;AAEzB,IAAA,MAAM,YAAY,GAAG,MAAM,aAAa;IACxC,IAAI,CAAC,YAAY,CAAC,YAAY;AAAE,QAAA,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC;AAC9E,IAAA,IAAI,YAAY,CAAC,aAAa,GAAG,qBAAqB,EAAE;;QAEpD,MAAM,IAAI,KAAK,CAAC,CAAA,4BAAA,EAA+B,qBAAqB,CAAA,2BAAA,EAA8B,YAAY,CAAC,aAAa,CAAA,CAAE,CAAC;IACnI;AACJ;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BG;AACG,SAAU,kBAAkB,CAM9B,UAAkB,EAClB,IAAY,EACZ,MAAyE,EACzE,OAAmC,EAAA;AAEnC,IAAA,IAAI,OAAO,EAAE,qBAAqB,KAAK,KAAK,EAAE;QAC1C,MAAM,CAAC,MAAM,CAACA,iCAAuB,EAAE,OAAO,EAAE,sBAAsB,CAAC;IAC3E;AAEA,IAAA,MAAM,CAAC,MAAM,CAACC,kCAAyB,CAAC;AACxC,IAAA,MAAM,CAAC,MAAM,CAACC,yBAAgB,CAAC;AAC/B,IAAA,MAAM,CAAC,GAAG,CAAC,YAAY,EAAE,OAAO,EAAE,UAAU,IAAI,MAAM,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,IAAI,CAAC;AACjF,IAAAC,gCAAqB,CAAC,gBAAgB,GAAG,MAAM,CAAC;;IAEhD,MAAM,UAAU,GAAG,OAAO,EAAE,UAAU,KAAKC,6BAAmB,CAAC,OAAO,KAAKC,iBAAQ,CAAC,gBAAgB,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,IAAI,2BAA2B,CAAC,CAAC;IAC7J,OAAO,UAAU,CAAC,KAAK,CAA+B,IAAI,EAAE,MAAM,EAAE,UAAU,CAAC;AACnF;AAEA;;;;;;;;;;;;;;;;AAgBG;AACI,eAAe,oCAAoC,CAMtD,kBAAiD,EACjD,KAAoF,EACpF,YAAuB,EAAA;IAEvB,IAAI,OAAO,kBAAkB,KAAK,QAAQ,IAAI,kBAAkB,YAAYC,cAAK,CAAC,QAAQ,EAAE;AACxF,QAAA,QAAQ,MAAM,KAAK,CAAC,QAAQ,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,YAAY,IAAI,EAAE,CAAC;IAC/E;AAEA,IAAA,OAAO,kBAAkB;AAC7B;;;;;;"}
1
+ {"version":3,"file":"utils.cjs","sources":["../src/utils.ts"],"sourcesContent":["import mongoose, { Types } from 'mongoose';\nimport type {\n mongo,\n Schema,\n} from 'mongoose';\nimport mongooseAggregatePaginate from 'mongoose-aggregate-paginate-v2';\nimport mongoosePaginate from 'mongoose-paginate-v2';\n\nimport { customMongooseOptions } from './_internals';\nimport { mongooseConnections } from './constants';\nimport type { setCustomMongooseOptions } from './options';\nimport { mongooseNormalizePlugin } from './plugins/normalize';\nimport type { BuildMongooseModelOptions } from './types/options';\n\nexport type DoNotRemoveOrUseThisType = typeof setCustomMongooseOptions;\n\n/**\n * Asserts that a Mongoose update operation was successful by checking that it was acknowledged\n * and that at least the expected number of documents were modified.\n *\n * This function is intended for use with `updateOne`, `updateMany`, or any update operation\n * that returns a MongoDB `UpdateResult`.\n *\n * @template T - The shape of the document being updated.\n * @param updatePromise - A promise returned from a Mongoose update operation.\n * @param expectedModifiedCount - The minimum number of documents expected to be modified. Defaults to 1.\n * @throws Will throw an error if:\n * - The operation was not acknowledged by MongoDB,\n * - Fewer documents were modified than expected.\n */\nexport async function assertMongooseUpdateSuccess<T extends mongo.BSON.Document>(\n updatePromise: Promise<mongo.UpdateResult<T>>,\n expectedModifiedCount = 1,\n) {\n const updateResult = await updatePromise;\n if (!updateResult.acknowledged) throw new Error('Update was not acknowledged');\n if (updateResult.modifiedCount < expectedModifiedCount) {\n // eslint-disable-next-line style/max-len\n throw new Error(`Expected to modify at least ${expectedModifiedCount} document(s), but modified ${updateResult.modifiedCount}`);\n }\n}\n\n/**\n * Builds and returns a Mongoose model with specified schema and options.\n *\n * This function sets up a Mongoose model with optional plugins and timestamp settings.\n * It can optionally use a specified connection or the default connection.\n *\n * Determine the connection to use:\n * 1. Use the connection provided in the options, if available.\n * 2. Otherwise, use the default connection stored in `mongooseConnections`.\n * 3. If there's no default connection, create one using the MongoDB URI from the environment variables,\n * or fallback to a local MongoDB instance.\n *\n * You can set a function to be executed before the final build by using {@link setCustomMongooseOptions}.\n * However, ensure that this option is configured before calling {@link buildMongooseModel}.\n *\n * @template DocType - The type of the document.\n * @template Model - The type of the model, which extends `BaseMongoosePaginateModel`.\n * @template InstanceMethodsAndOverrides - The type for instance methods and overrides.\n * @template QueryHelpers - The type for additional query helpers.\n *\n * @param collection - The name of the collection.\n * @param name - The name of the model.\n * @param schema - The Mongoose schema to use for the model.\n * @param options - Optional settings for building the model.\n *\n * @returns The created Mongoose model.\n */\nexport function buildMongooseModel<\n DocType,\n Model extends BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n InstanceMethodsAndOverrides = object,\n QueryHelpers = object,\n>(\n collection: string,\n name: string,\n schema: Schema<DocType, Model, InstanceMethodsAndOverrides, QueryHelpers>,\n options?: BuildMongooseModelOptions,\n) {\n if (options?.enableNormalizePlugin !== false) {\n schema.plugin(mongooseNormalizePlugin, options?.normalizePluginOptions);\n }\n\n schema.plugin(mongooseAggregatePaginate);\n schema.plugin(mongoosePaginate);\n schema.set('timestamps', options?.timestamps ?? schema.get('timestamps') ?? true);\n customMongooseOptions.beforeModelBuild?.(schema);\n // eslint-disable-next-line style/max-len\n const connection = options?.connection || (mongooseConnections.default ||= mongoose.createConnection(process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017'));\n return connection.model<DocType, Model, QueryHelpers>(name, schema, collection);\n}\n\n/**\n * Converts a document or ObjectId to a document using the specified model.\n *\n * This function takes a document or ObjectId and returns the corresponding document\n * from the database using the specified model. Optionally, specific fields can be selected.\n *\n * @template D - The type of the hydrated document.\n * @template DocType - The type of the document.\n * @template InstanceMethodsAndOverrides - The type for instance methods and overrides.\n * @template QueryHelpers - The type for additional query helpers.\n *\n * @param documentOrObjectId - The document or ObjectId to convert.\n * @param model - The Mongoose model to use for the conversion.\n * @param selectFields - Optional fields to select from the document.\n *\n * @returns The corresponding document or null if not found.\n */\nexport async function mongooseDocumentOrObjectIdToDocument<\n D extends MongooseHydratedDocument<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n DocType,\n InstanceMethodsAndOverrides,\n QueryHelpers,\n>(\n documentOrObjectId: MongooseDocumentOrObjectId<D>,\n model: BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n selectFields?: string[],\n) {\n if (typeof documentOrObjectId === 'string' || documentOrObjectId instanceof Types.ObjectId) {\n return (await model.findById(documentOrObjectId).select(selectFields || [])) as D | null;\n }\n\n return documentOrObjectId;\n}\n\n/**\n * Converts the input, which can be a MongoDB ObjectId or a string,\n * into a 24-character hexadecimal string representation of the ObjectId.\n *\n * @param {string | Types.ObjectId} id - The ObjectId instance or its string representation\n *\n * @returns {string} The hexadecimal string representation of the ObjectId\n */\nexport function toObjectIdHexString(id: string | Types.ObjectId) {\n return id instanceof Types.ObjectId ? id.toHexString() : id;\n}\n"],"names":["mongooseNormalizePlugin","mongooseAggregatePaginate","mongoosePaginate","customMongooseOptions","mongooseConnections","mongoose","Types"],"mappings":";;;;;;;;;;;;;;;AAgBA;;;;;;;;;;;;;AAaG;AACI,eAAe,2BAA2B,CAC7C,aAA6C,EAC7C,qBAAqB,GAAG,CAAC,EAAA;AAEzB,IAAA,MAAM,YAAY,GAAG,MAAM,aAAa;IACxC,IAAI,CAAC,YAAY,CAAC,YAAY;AAAE,QAAA,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC;AAC9E,IAAA,IAAI,YAAY,CAAC,aAAa,GAAG,qBAAqB,EAAE;;QAEpD,MAAM,IAAI,KAAK,CAAC,CAAA,4BAAA,EAA+B,qBAAqB,CAAA,2BAAA,EAA8B,YAAY,CAAC,aAAa,CAAA,CAAE,CAAC;IACnI;AACJ;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BG;AACG,SAAU,kBAAkB,CAM9B,UAAkB,EAClB,IAAY,EACZ,MAAyE,EACzE,OAAmC,EAAA;AAEnC,IAAA,IAAI,OAAO,EAAE,qBAAqB,KAAK,KAAK,EAAE;QAC1C,MAAM,CAAC,MAAM,CAACA,iCAAuB,EAAE,OAAO,EAAE,sBAAsB,CAAC;IAC3E;AAEA,IAAA,MAAM,CAAC,MAAM,CAACC,kCAAyB,CAAC;AACxC,IAAA,MAAM,CAAC,MAAM,CAACC,yBAAgB,CAAC;AAC/B,IAAA,MAAM,CAAC,GAAG,CAAC,YAAY,EAAE,OAAO,EAAE,UAAU,IAAI,MAAM,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,IAAI,CAAC;AACjF,IAAAC,gCAAqB,CAAC,gBAAgB,GAAG,MAAM,CAAC;;IAEhD,MAAM,UAAU,GAAG,OAAO,EAAE,UAAU,KAAKC,6BAAmB,CAAC,OAAO,KAAKC,iBAAQ,CAAC,gBAAgB,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,IAAI,2BAA2B,CAAC,CAAC;IAC7J,OAAO,UAAU,CAAC,KAAK,CAA+B,IAAI,EAAE,MAAM,EAAE,UAAU,CAAC;AACnF;AAEA;;;;;;;;;;;;;;;;AAgBG;AACI,eAAe,oCAAoC,CAMtD,kBAAiD,EACjD,KAAoF,EACpF,YAAuB,EAAA;IAEvB,IAAI,OAAO,kBAAkB,KAAK,QAAQ,IAAI,kBAAkB,YAAYC,cAAK,CAAC,QAAQ,EAAE;AACxF,QAAA,QAAQ,MAAM,KAAK,CAAC,QAAQ,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,YAAY,IAAI,EAAE,CAAC;IAC/E;AAEA,IAAA,OAAO,kBAAkB;AAC7B;AAEA;;;;;;;AAOG;AACG,SAAU,mBAAmB,CAAC,EAA2B,EAAA;AAC3D,IAAA,OAAO,EAAE,YAAYA,cAAK,CAAC,QAAQ,GAAG,EAAE,CAAC,WAAW,EAAE,GAAG,EAAE;AAC/D;;;;;;;"}
package/dist/utils.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { Types } from 'mongoose';
1
2
  import type { mongo, Schema } from 'mongoose';
2
3
  import type { setCustomMongooseOptions } from './options';
3
4
  import type { BuildMongooseModelOptions } from './types/options';
@@ -63,4 +64,13 @@ export declare function buildMongooseModel<DocType, Model extends BaseMongoosePa
63
64
  * @returns The corresponding document or null if not found.
64
65
  */
65
66
  export declare function mongooseDocumentOrObjectIdToDocument<D extends MongooseHydratedDocument<DocType, InstanceMethodsAndOverrides, QueryHelpers>, DocType, InstanceMethodsAndOverrides, QueryHelpers>(documentOrObjectId: MongooseDocumentOrObjectId<D>, model: BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>, selectFields?: string[]): Promise<D | null>;
67
+ /**
68
+ * Converts the input, which can be a MongoDB ObjectId or a string,
69
+ * into a 24-character hexadecimal string representation of the ObjectId.
70
+ *
71
+ * @param {string | Types.ObjectId} id - The ObjectId instance or its string representation
72
+ *
73
+ * @returns {string} The hexadecimal string representation of the ObjectId
74
+ */
75
+ export declare function toObjectIdHexString(id: string | Types.ObjectId): string;
66
76
  //# sourceMappingURL=utils.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACR,KAAK,EACL,MAAM,EACT,MAAM,UAAU,CAAC;AAMlB,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,WAAW,CAAC;AAE1D,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,iBAAiB,CAAC;AAEjE,MAAM,MAAM,wBAAwB,GAAG,OAAO,wBAAwB,CAAC;AAEvE;;;;;;;;;;;;;GAaG;AACH,wBAAsB,2BAA2B,CAAC,CAAC,SAAS,KAAK,CAAC,IAAI,CAAC,QAAQ,EAC3E,aAAa,EAAE,OAAO,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,EAC7C,qBAAqB,SAAI,iBAQ5B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,kBAAkB,CAC9B,OAAO,EACP,KAAK,SAAS,yBAAyB,CAAC,OAAO,EAAE,2BAA2B,EAAE,YAAY,CAAC,EAC3F,2BAA2B,GAAG,MAAM,EACpC,YAAY,GAAG,MAAM,EAErB,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,CAAC,OAAO,EAAE,KAAK,EAAE,2BAA2B,EAAE,YAAY,CAAC,EACzE,OAAO,CAAC,EAAE,yBAAyB,SAatC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,oCAAoC,CACtD,C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,oCAAoC,CACtD,CAAC,SAAS,wBAAwB,CAAC,OAAO,EAAE,2BAA2B,EAAE,YAAY,CAAC,EACtF,OAAO,EACP,2BAA2B,EAC3B,YAAY,EAEZ,kBAAkB,EAAE,0BAA0B,CAAC,CAAC,CAAC,EACjD,KAAK,EAAE,yBAAyB,CAAC,OAAO,EAAE,2BAA2B,EAAE,YAAY,CAAC,EACpF,YAAY,CAAC,EAAE,MAAM,EAAE,qBAO1B;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,EAAE,EAAE,MAAM,GAAG,KAAK,CAAC,QAAQ,UAE9D"}
package/dist/utils.mjs CHANGED
@@ -90,6 +90,17 @@ async function mongooseDocumentOrObjectIdToDocument(documentOrObjectId, model, s
90
90
  }
91
91
  return documentOrObjectId;
92
92
  }
93
+ /**
94
+ * Converts the input, which can be a MongoDB ObjectId or a string,
95
+ * into a 24-character hexadecimal string representation of the ObjectId.
96
+ *
97
+ * @param {string | Types.ObjectId} id - The ObjectId instance or its string representation
98
+ *
99
+ * @returns {string} The hexadecimal string representation of the ObjectId
100
+ */
101
+ function toObjectIdHexString(id) {
102
+ return id instanceof Types.ObjectId ? id.toHexString() : id;
103
+ }
93
104
 
94
- export { assertMongooseUpdateSuccess, buildMongooseModel, mongooseDocumentOrObjectIdToDocument };
105
+ export { assertMongooseUpdateSuccess, buildMongooseModel, mongooseDocumentOrObjectIdToDocument, toObjectIdHexString };
95
106
  //# sourceMappingURL=utils.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.mjs","sources":["../src/utils.ts"],"sourcesContent":["import mongoose, { Types } from 'mongoose';\nimport type {\n mongo,\n Schema,\n} from 'mongoose';\nimport mongooseAggregatePaginate from 'mongoose-aggregate-paginate-v2';\nimport mongoosePaginate from 'mongoose-paginate-v2';\n\nimport { customMongooseOptions } from './_internals';\nimport { mongooseConnections } from './constants';\nimport type { setCustomMongooseOptions } from './options';\nimport { mongooseNormalizePlugin } from './plugins/normalize';\nimport type { BuildMongooseModelOptions } from './types/options';\n\nexport type DoNotRemoveOrUseThisType = typeof setCustomMongooseOptions;\n\n/**\n * Asserts that a Mongoose update operation was successful by checking that it was acknowledged\n * and that at least the expected number of documents were modified.\n *\n * This function is intended for use with `updateOne`, `updateMany`, or any update operation\n * that returns a MongoDB `UpdateResult`.\n *\n * @template T - The shape of the document being updated.\n * @param updatePromise - A promise returned from a Mongoose update operation.\n * @param expectedModifiedCount - The minimum number of documents expected to be modified. Defaults to 1.\n * @throws Will throw an error if:\n * - The operation was not acknowledged by MongoDB,\n * - Fewer documents were modified than expected.\n */\nexport async function assertMongooseUpdateSuccess<T extends mongo.BSON.Document>(\n updatePromise: Promise<mongo.UpdateResult<T>>,\n expectedModifiedCount = 1,\n) {\n const updateResult = await updatePromise;\n if (!updateResult.acknowledged) throw new Error('Update was not acknowledged');\n if (updateResult.modifiedCount < expectedModifiedCount) {\n // eslint-disable-next-line style/max-len\n throw new Error(`Expected to modify at least ${expectedModifiedCount} document(s), but modified ${updateResult.modifiedCount}`);\n }\n}\n\n/**\n * Builds and returns a Mongoose model with specified schema and options.\n *\n * This function sets up a Mongoose model with optional plugins and timestamp settings.\n * It can optionally use a specified connection or the default connection.\n *\n * Determine the connection to use:\n * 1. Use the connection provided in the options, if available.\n * 2. Otherwise, use the default connection stored in `mongooseConnections`.\n * 3. If there's no default connection, create one using the MongoDB URI from the environment variables,\n * or fallback to a local MongoDB instance.\n *\n * You can set a function to be executed before the final build by using {@link setCustomMongooseOptions}.\n * However, ensure that this option is configured before calling {@link buildMongooseModel}.\n *\n * @template DocType - The type of the document.\n * @template Model - The type of the model, which extends `BaseMongoosePaginateModel`.\n * @template InstanceMethodsAndOverrides - The type for instance methods and overrides.\n * @template QueryHelpers - The type for additional query helpers.\n *\n * @param collection - The name of the collection.\n * @param name - The name of the model.\n * @param schema - The Mongoose schema to use for the model.\n * @param options - Optional settings for building the model.\n *\n * @returns The created Mongoose model.\n */\nexport function buildMongooseModel<\n DocType,\n Model extends BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n InstanceMethodsAndOverrides = object,\n QueryHelpers = object,\n>(\n collection: string,\n name: string,\n schema: Schema<DocType, Model, InstanceMethodsAndOverrides, QueryHelpers>,\n options?: BuildMongooseModelOptions,\n) {\n if (options?.enableNormalizePlugin !== false) {\n schema.plugin(mongooseNormalizePlugin, options?.normalizePluginOptions);\n }\n\n schema.plugin(mongooseAggregatePaginate);\n schema.plugin(mongoosePaginate);\n schema.set('timestamps', options?.timestamps ?? schema.get('timestamps') ?? true);\n customMongooseOptions.beforeModelBuild?.(schema);\n // eslint-disable-next-line style/max-len\n const connection = options?.connection || (mongooseConnections.default ||= mongoose.createConnection(process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017'));\n return connection.model<DocType, Model, QueryHelpers>(name, schema, collection);\n}\n\n/**\n * Converts a document or ObjectId to a document using the specified model.\n *\n * This function takes a document or ObjectId and returns the corresponding document\n * from the database using the specified model. Optionally, specific fields can be selected.\n *\n * @template D - The type of the hydrated document.\n * @template DocType - The type of the document.\n * @template InstanceMethodsAndOverrides - The type for instance methods and overrides.\n * @template QueryHelpers - The type for additional query helpers.\n *\n * @param documentOrObjectId - The document or ObjectId to convert.\n * @param model - The Mongoose model to use for the conversion.\n * @param selectFields - Optional fields to select from the document.\n *\n * @returns The corresponding document or null if not found.\n */\nexport async function mongooseDocumentOrObjectIdToDocument<\n D extends MongooseHydratedDocument<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n DocType,\n InstanceMethodsAndOverrides,\n QueryHelpers,\n>(\n documentOrObjectId: MongooseDocumentOrObjectId<D>,\n model: BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n selectFields?: string[],\n) {\n if (typeof documentOrObjectId === 'string' || documentOrObjectId instanceof Types.ObjectId) {\n return (await model.findById(documentOrObjectId).select(selectFields || [])) as D | null;\n }\n\n return documentOrObjectId;\n}\n"],"names":[],"mappings":";;;;;;;AAgBA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CAAoC,CAMtD,kBAAiD,EACjD,KAAoF,EACpF,YAAuB,EAAA;IAEvB,IAAI,OAAO,kBAAkB,KAAK,QAAQ,IAAI,kBAAkB,YAAY,KAAK,CAAC,QAAQ,EAAE;AACxF,QAAA,QAAQ,MAAM,KAAK,CAAC,QAAQ,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,YAAY,IAAI,EAAE,CAAC;IAC/E;AAEA,IAAA,OAAO,kBAAkB;AAC7B;;;;"}
1
+ {"version":3,"file":"utils.mjs","sources":["../src/utils.ts"],"sourcesContent":["import mongoose, { Types } from 'mongoose';\nimport type {\n mongo,\n Schema,\n} from 'mongoose';\nimport mongooseAggregatePaginate from 'mongoose-aggregate-paginate-v2';\nimport mongoosePaginate from 'mongoose-paginate-v2';\n\nimport { customMongooseOptions } from './_internals';\nimport { mongooseConnections } from './constants';\nimport type { setCustomMongooseOptions } from './options';\nimport { mongooseNormalizePlugin } from './plugins/normalize';\nimport type { BuildMongooseModelOptions } from './types/options';\n\nexport type DoNotRemoveOrUseThisType = typeof setCustomMongooseOptions;\n\n/**\n * Asserts that a Mongoose update operation was successful by checking that it was acknowledged\n * and that at least the expected number of documents were modified.\n *\n * This function is intended for use with `updateOne`, `updateMany`, or any update operation\n * that returns a MongoDB `UpdateResult`.\n *\n * @template T - The shape of the document being updated.\n * @param updatePromise - A promise returned from a Mongoose update operation.\n * @param expectedModifiedCount - The minimum number of documents expected to be modified. Defaults to 1.\n * @throws Will throw an error if:\n * - The operation was not acknowledged by MongoDB,\n * - Fewer documents were modified than expected.\n */\nexport async function assertMongooseUpdateSuccess<T extends mongo.BSON.Document>(\n updatePromise: Promise<mongo.UpdateResult<T>>,\n expectedModifiedCount = 1,\n) {\n const updateResult = await updatePromise;\n if (!updateResult.acknowledged) throw new Error('Update was not acknowledged');\n if (updateResult.modifiedCount < expectedModifiedCount) {\n // eslint-disable-next-line style/max-len\n throw new Error(`Expected to modify at least ${expectedModifiedCount} document(s), but modified ${updateResult.modifiedCount}`);\n }\n}\n\n/**\n * Builds and returns a Mongoose model with specified schema and options.\n *\n * This function sets up a Mongoose model with optional plugins and timestamp settings.\n * It can optionally use a specified connection or the default connection.\n *\n * Determine the connection to use:\n * 1. Use the connection provided in the options, if available.\n * 2. Otherwise, use the default connection stored in `mongooseConnections`.\n * 3. If there's no default connection, create one using the MongoDB URI from the environment variables,\n * or fallback to a local MongoDB instance.\n *\n * You can set a function to be executed before the final build by using {@link setCustomMongooseOptions}.\n * However, ensure that this option is configured before calling {@link buildMongooseModel}.\n *\n * @template DocType - The type of the document.\n * @template Model - The type of the model, which extends `BaseMongoosePaginateModel`.\n * @template InstanceMethodsAndOverrides - The type for instance methods and overrides.\n * @template QueryHelpers - The type for additional query helpers.\n *\n * @param collection - The name of the collection.\n * @param name - The name of the model.\n * @param schema - The Mongoose schema to use for the model.\n * @param options - Optional settings for building the model.\n *\n * @returns The created Mongoose model.\n */\nexport function buildMongooseModel<\n DocType,\n Model extends BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n InstanceMethodsAndOverrides = object,\n QueryHelpers = object,\n>(\n collection: string,\n name: string,\n schema: Schema<DocType, Model, InstanceMethodsAndOverrides, QueryHelpers>,\n options?: BuildMongooseModelOptions,\n) {\n if (options?.enableNormalizePlugin !== false) {\n schema.plugin(mongooseNormalizePlugin, options?.normalizePluginOptions);\n }\n\n schema.plugin(mongooseAggregatePaginate);\n schema.plugin(mongoosePaginate);\n schema.set('timestamps', options?.timestamps ?? schema.get('timestamps') ?? true);\n customMongooseOptions.beforeModelBuild?.(schema);\n // eslint-disable-next-line style/max-len\n const connection = options?.connection || (mongooseConnections.default ||= mongoose.createConnection(process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017'));\n return connection.model<DocType, Model, QueryHelpers>(name, schema, collection);\n}\n\n/**\n * Converts a document or ObjectId to a document using the specified model.\n *\n * This function takes a document or ObjectId and returns the corresponding document\n * from the database using the specified model. Optionally, specific fields can be selected.\n *\n * @template D - The type of the hydrated document.\n * @template DocType - The type of the document.\n * @template InstanceMethodsAndOverrides - The type for instance methods and overrides.\n * @template QueryHelpers - The type for additional query helpers.\n *\n * @param documentOrObjectId - The document or ObjectId to convert.\n * @param model - The Mongoose model to use for the conversion.\n * @param selectFields - Optional fields to select from the document.\n *\n * @returns The corresponding document or null if not found.\n */\nexport async function mongooseDocumentOrObjectIdToDocument<\n D extends MongooseHydratedDocument<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n DocType,\n InstanceMethodsAndOverrides,\n QueryHelpers,\n>(\n documentOrObjectId: MongooseDocumentOrObjectId<D>,\n model: BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n selectFields?: string[],\n) {\n if (typeof documentOrObjectId === 'string' || documentOrObjectId instanceof Types.ObjectId) {\n return (await model.findById(documentOrObjectId).select(selectFields || [])) as D | null;\n }\n\n return documentOrObjectId;\n}\n\n/**\n * Converts the input, which can be a MongoDB ObjectId or a string,\n * into a 24-character hexadecimal string representation of the ObjectId.\n *\n * @param {string | Types.ObjectId} id - The ObjectId instance or its string representation\n *\n * @returns {string} The hexadecimal string representation of the ObjectId\n */\nexport function toObjectIdHexString(id: string | Types.ObjectId) {\n return id instanceof Types.ObjectId ? id.toHexString() : id;\n}\n"],"names":[],"mappings":";;;;;;;AAgBA;;;;;;;;;;;;;AAaG;AACI,eAAe,2BAA2B,CAC7C,aAA6C,EAC7C,qBAAqB,GAAG,CAAC,EAAA;AAEzB,IAAA,MAAM,YAAY,GAAG,MAAM,aAAa;IACxC,IAAI,CAAC,YAAY,CAAC,YAAY;AAAE,QAAA,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC;AAC9E,IAAA,IAAI,YAAY,CAAC,aAAa,GAAG,qBAAqB,EAAE;;QAEpD,MAAM,IAAI,KAAK,CAAC,CAAA,4BAAA,EAA+B,qBAAqB,CAAA,2BAAA,EAA8B,YAAY,CAAC,aAAa,CAAA,CAAE,CAAC;IACnI;AACJ;A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E,CAAC,WAAW,EAAE,GAAG,EAAE;AAC/D;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kikiutils/mongoose",
3
- "version": "3.3.0",
3
+ "version": "4.0.1",
4
4
  "description": "A Mongoose plugin for enhanced JSON normalization and common schema creation, with built-in support for pagination and automatic Decimal128 conversion.",
5
5
  "author": "kiki-kanri",
6
6
  "license": "MIT",
@@ -47,7 +47,7 @@
47
47
  "./src"
48
48
  ],
49
49
  "engines": {
50
- "node": ">=18.12.1"
50
+ "node": ">=20.0.0"
51
51
  },
52
52
  "scripts": {
53
53
  "build": "ts-project-builder './src/**/*.ts' --clean --preserve-modules --sourcemaps",
@@ -65,22 +65,22 @@
65
65
  "dependencies": {
66
66
  "decimal.js": "^10.6.0",
67
67
  "lodash": "^4.17.21",
68
- "mongoose": "^8.16.3",
68
+ "mongoose": "^8.18.1",
69
69
  "mongoose-aggregate-paginate-v2": "^1.1.4",
70
70
  "mongoose-paginate-v2": "^1.9.1",
71
71
  "type-fest": "^4.41.0"
72
72
  },
73
73
  "devDependencies": {
74
- "@kikiutils/changelogen": "^0.8.1",
75
- "@kikiutils/eslint-config": "^1.2.7",
74
+ "@kikiutils/changelogen": "^0.9.0",
75
+ "@kikiutils/eslint-config": "^2.1.1",
76
76
  "@kikiutils/tsconfigs": "^5.0.4",
77
77
  "@types/lodash": "^4.17.20",
78
- "@types/node": "^24.0.14",
78
+ "@types/node": "^24.3.1",
79
79
  "@vitest/coverage-v8": "^3.2.4",
80
80
  "depcheck": "^1.4.7",
81
81
  "ts-project-builder": "^5.0.2",
82
82
  "ts-unused-exports": "^11.0.1",
83
- "typescript": "^5.8.3",
83
+ "typescript": "^5.9.2",
84
84
  "vitest": "^3.2.4"
85
85
  },
86
86
  "pnpm": {
@@ -52,8 +52,11 @@ export function mongooseNormalizePlugin<S extends Schema>(schema: S, pluginOptio
52
52
  _id = _id instanceof Types.ObjectId ? _id.toHexString() : _id;
53
53
  }
54
54
 
55
- if (pluginOptions?.convertIdField !== false) copiedRet.id = _id;
56
- else copiedRet._id = _id;
55
+ if (_id !== undefined) {
56
+ if (pluginOptions?.convertIdField !== false) copiedRet.id = _id;
57
+ else copiedRet._id = _id;
58
+ }
59
+
57
60
  for (const path in schema.paths) {
58
61
  if (schema.paths[path]?.options?.private) lodashUnset(copiedRet, path);
59
62
  if (schema.paths[path]?.instance === 'Decimal128') {
package/src/types/data.ts CHANGED
@@ -1,4 +1,3 @@
1
- import type { Types } from 'mongoose';
2
1
  import type { SetFieldType } from 'type-fest';
3
2
 
4
3
  import type { IfElse } from './utils';
@@ -25,7 +24,7 @@ declare global {
25
24
  CreatedAtField extends boolean = true,
26
25
  UpdatedAtField extends boolean = true,
27
26
  > = BaseMongooseDocType<
28
- SetFieldType<SetFieldType<T, DateFields, Date>, ObjectIdFields, Types.ObjectId>,
27
+ SetFieldsToObjectId<SetFieldType<T, DateFields, Date>, ObjectIdFields>,
29
28
  CreatedAtField,
30
29
  UpdatedAtField
31
30
  >;
@@ -123,5 +123,5 @@ declare global {
123
123
  QueryHelpers
124
124
  >;
125
125
 
126
- type SetFieldsToObjectId<T, F extends keyof T> = SetFieldType<T, F, Types.ObjectId>;
126
+ type SetFieldsToObjectId<T, K extends keyof T> = SetFieldType<T, K, Types.ObjectId>;
127
127
  }
package/src/utils.ts CHANGED
@@ -124,3 +124,15 @@ export async function mongooseDocumentOrObjectIdToDocument<
124
124
 
125
125
  return documentOrObjectId;
126
126
  }
127
+
128
+ /**
129
+ * Converts the input, which can be a MongoDB ObjectId or a string,
130
+ * into a 24-character hexadecimal string representation of the ObjectId.
131
+ *
132
+ * @param {string | Types.ObjectId} id - The ObjectId instance or its string representation
133
+ *
134
+ * @returns {string} The hexadecimal string representation of the ObjectId
135
+ */
136
+ export function toObjectIdHexString(id: string | Types.ObjectId) {
137
+ return id instanceof Types.ObjectId ? id.toHexString() : id;
138
+ }