@kikiutils/mongoose 3.0.3 → 3.1.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.
@@ -3,6 +3,7 @@
3
3
  const lodashGet = require('lodash/get.js');
4
4
  const lodashSet = require('lodash/set.js');
5
5
  const lodashUnset = require('lodash/unset.js');
6
+ const mongoose = require('mongoose');
6
7
 
7
8
  const _interopDefaultCompat = e => e && typeof e === 'object' && 'default' in e ? e.default : e;
8
9
 
@@ -10,6 +11,7 @@ const lodashGet__default = /*#__PURE__*/_interopDefaultCompat(lodashGet);
10
11
  const lodashSet__default = /*#__PURE__*/_interopDefaultCompat(lodashSet);
11
12
  const lodashUnset__default = /*#__PURE__*/_interopDefaultCompat(lodashUnset);
12
13
 
14
+ // @ts-expect-error Ignore this error.
13
15
  /**
14
16
  * Mongoose plugin to normalize the JSON output of documents.
15
17
  *
@@ -24,15 +26,21 @@ const lodashUnset__default = /*#__PURE__*/_interopDefaultCompat(lodashUnset);
24
26
  *
25
27
  * @param schema - The Mongoose schema to apply the plugin to.
26
28
  */
27
- function mongooseNormalizePlugin(schema) {
29
+ function mongooseNormalizePlugin(schema, pluginOptions) {
28
30
  const toJson = schema.get('toJSON');
29
31
  const toJsonTransform = toJson?.transform;
30
32
  schema.set('toJSON', {
31
33
  ...toJson,
32
34
  transform(doc, ret, options) {
33
- const copiedRet = { ...ret };
34
- copiedRet.id = copiedRet._id?.toHexString();
35
- delete copiedRet._id;
35
+ // eslint-disable-next-line style/object-curly-newline
36
+ let { __v, _id, ...copiedRet } = ret;
37
+ if (pluginOptions?.toHexIdIfObjectId !== false) {
38
+ _id = _id instanceof mongoose.Types.ObjectId ? _id.toHexString() : _id;
39
+ }
40
+ if (pluginOptions?.convertIdField !== false)
41
+ copiedRet.id = _id;
42
+ else
43
+ copiedRet._id = _id;
36
44
  for (const path in schema.paths) {
37
45
  if (schema.paths[path]?.options?.private)
38
46
  lodashUnset__default(copiedRet, path);
@@ -42,7 +50,6 @@ function mongooseNormalizePlugin(schema) {
42
50
  lodashSet__default(copiedRet, path, value.toString());
43
51
  }
44
52
  }
45
- delete copiedRet.__v;
46
53
  if (toJsonTransform && typeof toJsonTransform !== 'boolean') {
47
54
  return toJsonTransform(doc, copiedRet, options);
48
55
  }
@@ -1 +1 @@
1
- {"version":3,"file":"normalize.cjs","sources":["../../src/plugins/normalize.ts"],"sourcesContent":["import lodashGet from 'lodash/get.js';\nimport lodashSet from 'lodash/set.js';\nimport lodashUnset from 'lodash/unset.js';\nimport type {\n Schema,\n Types,\n} from 'mongoose';\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) {\n const toJson = schema.get('toJSON');\n const toJsonTransform = toJson?.transform;\n schema.set(\n 'toJSON',\n {\n ...toJson,\n transform(doc: any, ret: any, options: any) {\n const copiedRet = { ...ret };\n copiedRet.id = copiedRet._id?.toHexString();\n delete copiedRet._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 delete copiedRet.__v;\n if (toJsonTransform && typeof toJsonTransform !== 'boolean') {\n return toJsonTransform(doc, copiedRet, options);\n }\n\n return copiedRet;\n },\n },\n );\n}\n"],"names":["lodashUnset","lodashGet","lodashSet"],"mappings":";;;;;;;;;;;;AAQA;;;;;;;;;;;;;AAaG;AACG,SAAU,uBAAuB,CAAmB,MAAS,EAAA;IAC/D,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,GAAQ,EAAE,GAAQ,EAAE,OAAY,EAAA;AACtC,YAAA,MAAM,SAAS,GAAG,EAAE,GAAG,GAAG,EAAE;YAC5B,SAAS,CAAC,EAAE,GAAG,SAAS,CAAC,GAAG,EAAE,WAAW,EAAE;YAC3C,OAAO,SAAS,CAAC,GAAG;AACpB,YAAA,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,KAAK,EAAE;gBAC7B,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,OAAO;AAAE,oBAAAA,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;;;YAI/D,OAAO,SAAS,CAAC,GAAG;AACpB,YAAA,IAAI,eAAe,IAAI,OAAO,eAAe,KAAK,SAAS,EAAE;gBACzD,OAAO,eAAe,CAAC,GAAG,EAAE,SAAS,EAAE,OAAO,CAAC;;AAGnD,YAAA,OAAO,SAAS;SACnB;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: any, ret: any, options: any) {\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, copiedRet, options);\n }\n\n return copiedRet;\n },\n },\n );\n}\n"],"names":["Types","lodashUnset","lodashGet","lodashSet"],"mappings":";;;;;;;;;;;;;AAAA;AA0BA;;;;;;;;;;;;;AAaG;AACa,SAAA,uBAAuB,CAAmB,MAAS,EAAE,aAA8C,EAAA;IAC/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@@ -1,4 +1,19 @@
1
1
  import type { Schema } from 'mongoose';
2
+ export interface MongooseNormalizePluginOptions {
3
+ /**
4
+ * Whether to convert `_id` field to `id`.
5
+ * If true, the `_id` field will be replaced with `id`.
6
+ *
7
+ * @default true
8
+ */
9
+ convertIdField?: boolean;
10
+ /**
11
+ * Whether to convert the `_id` field to a hex string if it's an ObjectId.
12
+ *
13
+ * @default true
14
+ */
15
+ toHexIdIfObjectId?: boolean;
16
+ }
2
17
  /**
3
18
  * Mongoose plugin to normalize the JSON output of documents.
4
19
  *
@@ -13,5 +28,5 @@ import type { Schema } from 'mongoose';
13
28
  *
14
29
  * @param schema - The Mongoose schema to apply the plugin to.
15
30
  */
16
- export declare function mongooseNormalizePlugin<S extends Schema>(schema: S): void;
31
+ export declare function mongooseNormalizePlugin<S extends Schema>(schema: S, pluginOptions?: MongooseNormalizePluginOptions): void;
17
32
  //# sourceMappingURL=normalize.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"normalize.d.ts","sourceRoot":"","sources":["../../src/plugins/normalize.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACR,MAAM,EAET,MAAM,UAAU,CAAC;AAElB;;;;;;;;;;;;;GAaG;AACH,wBAAgB,uBAAuB,CAAC,CAAC,SAAS,MAAM,EAAE,MAAM,EAAE,CAAC,QA4BlE"}
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,7 +1,9 @@
1
1
  import lodashGet from 'lodash/get.js';
2
2
  import lodashSet from 'lodash/set.js';
3
3
  import lodashUnset from 'lodash/unset.js';
4
+ import { Types } from 'mongoose';
4
5
 
6
+ // @ts-expect-error Ignore this error.
5
7
  /**
6
8
  * Mongoose plugin to normalize the JSON output of documents.
7
9
  *
@@ -16,15 +18,21 @@ import lodashUnset from 'lodash/unset.js';
16
18
  *
17
19
  * @param schema - The Mongoose schema to apply the plugin to.
18
20
  */
19
- function mongooseNormalizePlugin(schema) {
21
+ function mongooseNormalizePlugin(schema, pluginOptions) {
20
22
  const toJson = schema.get('toJSON');
21
23
  const toJsonTransform = toJson?.transform;
22
24
  schema.set('toJSON', {
23
25
  ...toJson,
24
26
  transform(doc, ret, options) {
25
- const copiedRet = { ...ret };
26
- copiedRet.id = copiedRet._id?.toHexString();
27
- delete copiedRet._id;
27
+ // eslint-disable-next-line style/object-curly-newline
28
+ let { __v, _id, ...copiedRet } = ret;
29
+ if (pluginOptions?.toHexIdIfObjectId !== false) {
30
+ _id = _id instanceof Types.ObjectId ? _id.toHexString() : _id;
31
+ }
32
+ if (pluginOptions?.convertIdField !== false)
33
+ copiedRet.id = _id;
34
+ else
35
+ copiedRet._id = _id;
28
36
  for (const path in schema.paths) {
29
37
  if (schema.paths[path]?.options?.private)
30
38
  lodashUnset(copiedRet, path);
@@ -34,7 +42,6 @@ function mongooseNormalizePlugin(schema) {
34
42
  lodashSet(copiedRet, path, value.toString());
35
43
  }
36
44
  }
37
- delete copiedRet.__v;
38
45
  if (toJsonTransform && typeof toJsonTransform !== 'boolean') {
39
46
  return toJsonTransform(doc, copiedRet, options);
40
47
  }
@@ -1 +1 @@
1
- {"version":3,"file":"normalize.mjs","sources":["../../src/plugins/normalize.ts"],"sourcesContent":["import lodashGet from 'lodash/get.js';\nimport lodashSet from 'lodash/set.js';\nimport lodashUnset from 'lodash/unset.js';\nimport type {\n Schema,\n Types,\n} from 'mongoose';\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) {\n const toJson = schema.get('toJSON');\n const toJsonTransform = toJson?.transform;\n schema.set(\n 'toJSON',\n {\n ...toJson,\n transform(doc: any, ret: any, options: any) {\n const copiedRet = { ...ret };\n copiedRet.id = copiedRet._id?.toHexString();\n delete copiedRet._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 delete copiedRet.__v;\n if (toJsonTransform && typeof toJsonTransform !== 'boolean') {\n return toJsonTransform(doc, copiedRet, options);\n }\n\n return copiedRet;\n },\n },\n );\n}\n"],"names":[],"mappings":";;;;AAQA;;;;;;;;;;;;;AAaG;AACG,SAAU,uBAAuB,CAAmB,MAAS,EAAA;IAC/D,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,GAAQ,EAAE,GAAQ,EAAE,OAAY,EAAA;AACtC,YAAA,MAAM,SAAS,GAAG,EAAE,GAAG,GAAG,EAAE;YAC5B,SAAS,CAAC,EAAE,GAAG,SAAS,CAAC,GAAG,EAAE,WAAW,EAAE;YAC3C,OAAO,SAAS,CAAC,GAAG;AACpB,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;;;YAI/D,OAAO,SAAS,CAAC,GAAG;AACpB,YAAA,IAAI,eAAe,IAAI,OAAO,eAAe,KAAK,SAAS,EAAE;gBACzD,OAAO,eAAe,CAAC,GAAG,EAAE,SAAS,EAAE,OAAO,CAAC;;AAGnD,YAAA,OAAO,SAAS;SACnB;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: any, ret: any, options: any) {\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, copiedRet, options);\n }\n\n return copiedRet;\n },\n },\n );\n}\n"],"names":[],"mappings":";;;;;AAAA;AA0BA;;;;;;;;;;;;;AAaG;AACa,SAAA,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,GAAQ,EAAE,GAAQ,EAAE,OAAY,EAAA;;YAEtC,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;;AAGjE,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;;;AAI/D,YAAA,IAAI,eAAe,IAAI,OAAO,eAAe,KAAK,SAAS,EAAE;gBACzD,OAAO,eAAe,CAAC,GAAG,EAAE,SAAS,EAAE,OAAO,CAAC;;AAGnD,YAAA,OAAO,SAAS;SACnB;AACJ,KAAA,CACJ;AACL;;;;"}
@@ -1,4 +1,5 @@
1
1
  import type { Connection, Schema, SchemaTimestampsConfig } from 'mongoose';
2
+ import type { MongooseNormalizePluginOptions } from '../plugins/normalize';
2
3
  import type { buildMongooseModel } from '../utils';
3
4
  export type DoNotRemoveOrUseThisType = typeof buildMongooseModel;
4
5
  /**
@@ -25,6 +26,7 @@ export interface BuildMongooseModelOptions {
25
26
  * @default true
26
27
  */
27
28
  enableNormalizePlugin?: boolean;
29
+ normalizePluginOptions?: MongooseNormalizePluginOptions;
28
30
  /**
29
31
  * Configures Mongoose timestamps.
30
32
  *
@@ -1 +1 @@
1
- {"version":3,"file":"options.d.ts","sourceRoot":"","sources":["../../src/types/options.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACR,UAAU,E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,CAAC,EAAE,OAAO,GAAG,sBAAsB,CAAC;CACjD;AAED,MAAM,WAAW,qBAAqB;IAClC;;OAEG;IACH,gBAAgB,CAAC,EAAE,CACf,OAAO,EACP,KAAK,SAAS,yBAAyB,CAAC,OAAO,EAAE,2BAA2B,EAAE,YAAY,CAAC,EAC3F,2BAA2B,GAAG,MAAM,EACpC,YAAY,GAAG,MAAM,EAErB,MAAM,EAAE,MAAM,CACV,OAAO,EACP,KAAK,EACL,2BAA2B,EAC3B,YAAY,CACf,KACA,IAAI,CAAC;CACb"}
package/dist/utils.cjs CHANGED
@@ -64,8 +64,9 @@ async function assertMongooseUpdateSuccess(updatePromise, expectedModifiedCount
64
64
  * @returns The created Mongoose model.
65
65
  */
66
66
  function buildMongooseModel(collection, name, schema, options) {
67
- if (options?.enableNormalizePlugin !== false)
68
- schema.plugin(normalize.mongooseNormalizePlugin);
67
+ if (options?.enableNormalizePlugin !== false) {
68
+ schema.plugin(normalize.mongooseNormalizePlugin, options?.normalizePluginOptions);
69
+ }
69
70
  schema.plugin(mongooseAggregatePaginate__default);
70
71
  schema.plugin(mongoosePaginate__default);
71
72
  schema.set('timestamps', options?.timestamps ?? schema.get('timestamps') ?? true);
@@ -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) schema.plugin(mongooseNormalizePlugin);\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,Y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AAE;AACxF,QAAA,QAAQ,MAAM,KAAK,CAAC,QAAQ,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,YAAY,IAAI,EAAE,CAAC;;AAG/E,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"],"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,8BAA8B,CAAC;AAC/E,IAAA,IAAI,YAAY,CAAC,aAAa,GAAG,qBAAqB,EAAE;;QAEpD,MAAM,IAAI,KAAK,CAAC,CAA+B,4BAAA,EAAA,qBAAqB,CAA8B,2BAAA,EAAA,YAAY,CAAC,aAAa,CAAG,CAAA,CAAA,CAAC;;AAExI;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;;AAG3E,IAAA,MAAM,CAAC,M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a,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,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"}
package/dist/utils.mjs CHANGED
@@ -56,8 +56,9 @@ async function assertMongooseUpdateSuccess(updatePromise, expectedModifiedCount
56
56
  * @returns The created Mongoose model.
57
57
  */
58
58
  function buildMongooseModel(collection, name, schema, options) {
59
- if (options?.enableNormalizePlugin !== false)
60
- schema.plugin(mongooseNormalizePlugin);
59
+ if (options?.enableNormalizePlugin !== false) {
60
+ schema.plugin(mongooseNormalizePlugin, options?.normalizePluginOptions);
61
+ }
61
62
  schema.plugin(mongooseAggregatePaginate);
62
63
  schema.plugin(mongoosePaginate);
63
64
  schema.set('timestamps', options?.timestamps ?? schema.get('timestamps') ?? true);
@@ -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) schema.plugin(mongooseNormalizePlugin);\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;;;;;;;;;;;;;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,8BAA8B,CAAC;AAC/E,IAAA,IAAI,YAAY,CAAC,aAAa,GAAG,qBAAqB,EAAE;;QAEpD,MAAM,IAAI,KAAK,CAAC,CAA+B,4BAAA,EAAA,qBAAqB,CAA8B,2BAAA,EAAA,YAAY,CAAC,aAAa,CAAG,CAAA,CAAA,CAAC;;AAExI;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BG;AACG,SAAU,kBAAkB,CAM9B,UAAkB,EAClB,IAAY,EACZ,MAAyE,EACzE,OAAmC,EAAA;AAEnC,IAAA,IAAI,OAAO,EAAE,qBAAqB,KAAK,KAAK;AAAE,QAAA,MAAM,CAAC,MAAM,CAAC,uBAAuB,CAAC;AACpF,IAAA,MAAM,CAAC,MAAM,CAAC,yBAAyB,CAAC;AACxC,IAAA,MAAM,CAAC,MAAM,CAAC,gBAAgB,CAAC;AAC/B,IAAA,MAAM,CAAC,GAAG,CAAC,YAAY,EAAE,OAAO,EAAE,UAAU,IAAI,MAAM,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,IAAI,CAAC;AACjF,IAAA,qBAAqB,CAAC,gBAAgB,GAAG,MAAM,CAAC;;IAEhD,MAAM,UAAU,GAAG,OAAO,EAAE,UAAU,KAAK,mBAAmB,CAAC,OAAO,KAAK,QAAQ,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,YAAY,KAAK,CAAC,QAAQ,EAAE;AACxF,QAAA,QAAQ,MAAM,KAAK,CAAC,QAAQ,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,YAAY,IAAI,EAAE,CAAC;;AAG/E,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"],"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,8BAA8B,CAAC;AAC/E,IAAA,IAAI,YAAY,CAAC,aAAa,GAAG,qBAAqB,EAAE;;QAEpD,MAAM,IAAI,KAAK,CAAC,CAA+B,4BAAA,EAAA,qBAAqB,CAA8B,2BAAA,EAAA,YAAY,CAAC,aAAa,CAAG,CAAA,CAAA,CAAC;;AAExI;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,CAAC,uBAAuB,EAAE,OAAO,EAAE,sBAAsB,CAAC;;AAG3E,IAAA,MAAM,CAAC,MAAM,CAAC,yBAAyB,CAAC;AACxC,IAAA,MAAM,CAAC,MAAM,CAAC,gBAAgB,CAAC;AAC/B,IAAA,MAAM,CAAC,GAAG,CAAC,YAAY,EAAE,OAAO,EAAE,UAAU,IAAI,MAAM,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,IAAI,CAAC;AACjF,IAAA,qBAAqB,CAAC,gBAAgB,GAAG,MAAM,CAAC;;IAEhD,MAAM,UAAU,GAAG,OAAO,EAAE,UAAU,KAAK,mBAAmB,CAAC,OAAO,KAAK,QAAQ,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,YAAY,KAAK,CAAC,QAAQ,EAAE;AACxF,QAAA,QAAQ,MAAM,KAAK,CAAC,QAAQ,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,YAAY,IAAI,EAAE,CAAC;;AAG/E,IAAA,OAAO,kBAAkB;AAC7B;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kikiutils/mongoose",
3
- "version": "3.0.3",
3
+ "version": "3.1.0",
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",
@@ -67,14 +67,14 @@
67
67
  },
68
68
  "devDependencies": {
69
69
  "@kikiutils/changelogen": "^0.8.0",
70
- "@kikiutils/eslint-config": "^0.12.0",
71
- "@kikiutils/tsconfigs": "^4.0.0",
70
+ "@kikiutils/eslint-config": "^0.12.2",
71
+ "@kikiutils/tsconfigs": "^4.1.0",
72
72
  "@types/jest": "^29.5.14",
73
73
  "@types/lodash": "^4.17.16",
74
- "@types/node": "^22.14.0",
74
+ "@types/node": "^22.14.1",
75
75
  "jest": "^29.7.0",
76
- "ts-jest": "^29.3.1",
77
- "ts-project-builder": "^4.0.0"
76
+ "ts-jest": "^29.3.2",
77
+ "ts-project-builder": "^4.0.1"
78
78
  },
79
79
  "pnpm": {
80
80
  "onlyBuiltDependencies": [
@@ -1,10 +1,28 @@
1
+ // @ts-expect-error Ignore this error.
1
2
  import lodashGet from 'lodash/get.js';
3
+ // @ts-expect-error Ignore this error.
2
4
  import lodashSet from 'lodash/set.js';
5
+ // @ts-expect-error Ignore this error.
3
6
  import lodashUnset from 'lodash/unset.js';
4
- import type {
5
- Schema,
6
- Types,
7
- } from 'mongoose';
7
+ import { Types } from 'mongoose';
8
+ import type { Schema } from 'mongoose';
9
+
10
+ export interface MongooseNormalizePluginOptions {
11
+ /**
12
+ * Whether to convert `_id` field to `id`.
13
+ * If true, the `_id` field will be replaced with `id`.
14
+ *
15
+ * @default true
16
+ */
17
+ convertIdField?: boolean;
18
+
19
+ /**
20
+ * Whether to convert the `_id` field to a hex string if it's an ObjectId.
21
+ *
22
+ * @default true
23
+ */
24
+ toHexIdIfObjectId?: boolean;
25
+ }
8
26
 
9
27
  /**
10
28
  * Mongoose plugin to normalize the JSON output of documents.
@@ -20,7 +38,7 @@ import type {
20
38
  *
21
39
  * @param schema - The Mongoose schema to apply the plugin to.
22
40
  */
23
- export function mongooseNormalizePlugin<S extends Schema>(schema: S) {
41
+ export function mongooseNormalizePlugin<S extends Schema>(schema: S, pluginOptions?: MongooseNormalizePluginOptions) {
24
42
  const toJson = schema.get('toJSON');
25
43
  const toJsonTransform = toJson?.transform;
26
44
  schema.set(
@@ -28,9 +46,14 @@ export function mongooseNormalizePlugin<S extends Schema>(schema: S) {
28
46
  {
29
47
  ...toJson,
30
48
  transform(doc: any, ret: any, options: any) {
31
- const copiedRet = { ...ret };
32
- copiedRet.id = copiedRet._id?.toHexString();
33
- delete copiedRet._id;
49
+ // eslint-disable-next-line style/object-curly-newline
50
+ let { __v, _id, ...copiedRet } = ret;
51
+ if (pluginOptions?.toHexIdIfObjectId !== false) {
52
+ _id = _id instanceof Types.ObjectId ? _id.toHexString() : _id;
53
+ }
54
+
55
+ if (pluginOptions?.convertIdField !== false) copiedRet.id = _id;
56
+ else copiedRet._id = _id;
34
57
  for (const path in schema.paths) {
35
58
  if (schema.paths[path]?.options?.private) lodashUnset(copiedRet, path);
36
59
  if (schema.paths[path]?.instance === 'Decimal128') {
@@ -39,7 +62,6 @@ export function mongooseNormalizePlugin<S extends Schema>(schema: S) {
39
62
  }
40
63
  }
41
64
 
42
- delete copiedRet.__v;
43
65
  if (toJsonTransform && typeof toJsonTransform !== 'boolean') {
44
66
  return toJsonTransform(doc, copiedRet, options);
45
67
  }
@@ -4,6 +4,7 @@ import type {
4
4
  SchemaTimestampsConfig,
5
5
  } from 'mongoose';
6
6
 
7
+ import type { MongooseNormalizePluginOptions } from '../plugins/normalize';
7
8
  import type { buildMongooseModel } from '../utils';
8
9
 
9
10
  export type DoNotRemoveOrUseThisType = typeof buildMongooseModel;
@@ -33,6 +34,7 @@ export interface BuildMongooseModelOptions {
33
34
  * @default true
34
35
  */
35
36
  enableNormalizePlugin?: boolean;
37
+ normalizePluginOptions?: MongooseNormalizePluginOptions;
36
38
 
37
39
  /**
38
40
  * Configures Mongoose timestamps.
package/src/utils.ts CHANGED
@@ -78,7 +78,10 @@ export function buildMongooseModel<
78
78
  schema: Schema<DocType, Model, InstanceMethodsAndOverrides, QueryHelpers>,
79
79
  options?: BuildMongooseModelOptions,
80
80
  ) {
81
- if (options?.enableNormalizePlugin !== false) schema.plugin(mongooseNormalizePlugin);
81
+ if (options?.enableNormalizePlugin !== false) {
82
+ schema.plugin(mongooseNormalizePlugin, options?.normalizePluginOptions);
83
+ }
84
+
82
85
  schema.plugin(mongooseAggregatePaginate);
83
86
  schema.plugin(mongoosePaginate);
84
87
  schema.set('timestamps', options?.timestamps ?? schema.get('timestamps') ?? true);