@kikiutils/mongoose 1.0.5 → 1.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.
package/README.md CHANGED
@@ -4,85 +4,42 @@
4
4
  [![npm downloads][npm-downloads-src]][npm-downloads-href]
5
5
  [![License][license-src]][license-href]
6
6
 
7
- This project provides types and utilities for Mongoose v8.
7
+ A Mongoose plugin for enhanced JSON normalization and common schema creation, with built-in support for pagination and automatic Decimal128 conversion.
8
8
 
9
9
  - [✨ Release Notes](./CHANGELOG.md)
10
10
 
11
11
  ## Features
12
12
 
13
- - Enhanced `toJSON` method with normalization functions:
14
- - Auto-converts `_id` to `id`
15
- - Removes `private` fields from the JSON output
16
- - Converts `Decimal128` fields to strings
17
- - Removes `__v` version key
18
- - Commonly used schema settings for fast schema creation with `createCommonMongooseSchemas`.
19
- - Automatic timestamp field settings based on configuration.
20
- - Pre-registered `mongoose-paginate-v2` and `mongoose-aggregate-paginate-v2` plugins for pagination support.
21
- - Automatic Decimal128 field conversion and rounding configuration.
22
- - TypeScript support for better type safety and IntelliSense.
23
- - Flexible model creation with `buildMongooseModel`, supporting custom connections and plugin configurations.
13
+ - ✨ Flexible Connections: Choose to use a specific connection or fall back to a default connection, with an automatic creation of a connection if none is provided
14
+ - ✨ Plugin Integration: Automatically integrates `mongoose-aggregate-paginate-v2`, `mongoose-paginate-v2`, and a custom normalization plugin for enhanced JSON output
15
+ - 🛠 Predefined Schemas: Provides a set of commonly used schema definitions such as boolean, decimal128, number, objectId, and string
16
+ - 🛠 Customizable: Allows for custom schemas and settings, including automatic rounding and fixed decimal places for `Decimal128` fields
17
+ - 🔄 Enhanced JSON Output: Adds an `id` field, removes `_id` and `__v` fields, excludes private fields, and converts `Decimal128` fields to strings in JSON output
18
+ - 🧩 Reference Schema Creation: Easily create schema definitions for ObjectId references with attributes like `private`, `required`, and `unique`
19
+ - 🧩 String Schema Creation: Generate string schema definitions with attributes such as `private`, `required`, `short`, `trim`, and `unique`
20
+ - 🧩 Decimal128 Field Conversion: Set up getters to convert `Decimal128` fields to strings for easier handling in documents
21
+ - 🧩 Document Conversion: Convert documents or ObjectIds to documents using specified models, with optional field selection
24
22
 
25
- ## Installation
26
-
27
- ```bash
28
- # Using pnpm
29
- pnpm add @kikiutils/mongoose
30
-
31
- # Using yarn
32
- yarn add @kikiutils/mongoose
33
-
34
- # Using npm
35
- npm i @kikiutils/mongoose
36
-
37
- # Using bun
38
- bun add @kikiutils/mongoose
39
- ```
40
-
41
- ## Environmental Requirements
42
-
43
- - ESM only
44
- - Mongoose v8
45
- - NodeJS 18 or higher
46
-
47
- ## Usage
23
+ ## Environment Requirements
48
24
 
49
- Example code is provided in the examples folder. Follow the steps below to understand how to use the package:
25
+ - Mongoose version 8.x
26
+ - Node.js version 18 or higher
50
27
 
51
- 1. Navigate to the examples folder
52
-
53
- ```bash
54
- cd examples
55
- ```
56
-
57
- 2. Install the dependencies
58
-
59
- ```bash
60
- pnpm i
61
- ```
28
+ ## Installation
62
29
 
63
- 3. Copy the .env.example file to .env
30
+ Add dependency (example using pnpm).
64
31
 
65
32
  ```bash
66
- cp .env.example .env
33
+ pnpm add @kikiutils/mongoose
67
34
  ```
68
35
 
69
- 4. Set the MONGODB_URI in the .env file with your MongoDB connection string
70
- 5. Run the example code
71
-
72
- - If you use bun, run this command directly
73
- ```bash
74
- bun --watch run ./src/index.ts
75
- ```
36
+ You can also use yarn, npm, or bun to add the dependency.
76
37
 
77
- - Use node
78
- ```bash
79
- pnpm run build
80
- MONGODB_URI="mongodb://127.0.0.1:27017/kikiutils-mongoose-test?directConnection=true" node ./dist/index.mjs
81
- ```
38
+ That's it! You're ready to use this package in your project. Check out the instructions for [usage](#usage) below ✨.
82
39
 
83
- This will execute the example code and demonstrate how to use the @kikiutils/mongoose package with your MongoDB setup.
40
+ # Usage
84
41
 
85
- You can modify the code in examples/src/index.ts and run it to test other functions.
42
+ Please refer to the [examples](./examples/README.md) folder for usage instructions of this package.
86
43
 
87
44
  ## License
88
45
 
package/constants.cjs ADDED
@@ -0,0 +1,23 @@
1
+ 'use strict';
2
+
3
+ const utils = require('./utils.cjs');
4
+
5
+ /**
6
+ * Common Mongoose schemas.
7
+ *
8
+ * This constant holds a set of commonly used Mongoose schema definitions, generated
9
+ * by the `createCommonMongooseSchemas` utility function. These schemas include common
10
+ * field types and configurations used across multiple models.
11
+ */
12
+ const commonMongooseSchemas = utils.createCommonMongooseSchemas();
13
+ /**
14
+ * Mongoose connections.
15
+ *
16
+ * This constant is a record of named Mongoose connections, allowing multiple
17
+ * database connections to be managed within the application. An optional `default`
18
+ * connection can also be specified for use when a specific connection is not provided.
19
+ */
20
+ const mongooseConnections = {};
21
+
22
+ exports.commonMongooseSchemas = commonMongooseSchemas;
23
+ exports.mongooseConnections = mongooseConnections;
package/constants.mjs CHANGED
@@ -1,4 +1,5 @@
1
- import { createCommonMongooseSchemas } from "./utils.mjs";
1
+ import { createCommonMongooseSchemas } from './utils.mjs';
2
+
2
3
  /**
3
4
  * Common Mongoose schemas.
4
5
  *
@@ -6,7 +7,7 @@ import { createCommonMongooseSchemas } from "./utils.mjs";
6
7
  * by the `createCommonMongooseSchemas` utility function. These schemas include common
7
8
  * field types and configurations used across multiple models.
8
9
  */
9
- export const commonMongooseSchemas = createCommonMongooseSchemas();
10
+ const commonMongooseSchemas = createCommonMongooseSchemas();
10
11
  /**
11
12
  * Mongoose connections.
12
13
  *
@@ -14,4 +15,6 @@ export const commonMongooseSchemas = createCommonMongooseSchemas();
14
15
  * database connections to be managed within the application. An optional `default`
15
16
  * connection can also be specified for use when a specific connection is not provided.
16
17
  */
17
- export const mongooseConnections = {};
18
+ const mongooseConnections = {};
19
+
20
+ export { commonMongooseSchemas, mongooseConnections };
package/package.json CHANGED
@@ -1,49 +1,58 @@
1
1
  {
2
2
  "name": "@kikiutils/mongoose",
3
- "version": "1.0.5",
4
- "description": "Types and utilities for Mongoose v8.",
3
+ "version": "1.1.0",
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
  "license": "MIT",
6
6
  "author": "kiki-kanri",
7
7
  "repository": {
8
8
  "type": "git",
9
9
  "url": "git+https://github.com/kiki-kanri/kikiutils-node-mongoose.git"
10
10
  },
11
- "type": "module",
12
11
  "scripts": {
13
- "build": "rm -rf ./dist && tsc-multi",
12
+ "build": "rollup -c --configPlugin typescript=\"{ tsconfig: './tsconfig.rollup.json' }\"",
14
13
  "bumplog": "changelogen --bump"
15
14
  },
16
15
  "dependencies": {
17
16
  "decimal.js": "^10.4.3",
18
- "lodash-es": "^4.17.21",
19
- "mongoose": "^8.4.5",
17
+ "lodash": "^4.17.21",
18
+ "mongoose": "^8.5.1",
20
19
  "mongoose-aggregate-paginate-v2": "^1.1.1",
21
20
  "mongoose-paginate-v2": "^1.8.2"
22
21
  },
23
22
  "devDependencies": {
24
23
  "@kikiutils/prettierrc": "^1.3.2",
25
- "@kikiutils/tsconfigs": "^2.2.0",
26
- "@types/lodash-es": "^4.17.12",
27
- "@types/node": "^20.14.10",
24
+ "@kikiutils/tsconfigs": "^3.0.1",
25
+ "@rollup/plugin-node-resolve": "^15.2.3",
26
+ "@rollup/plugin-typescript": "^11.1.6",
27
+ "@types/lodash": "^4.17.7",
28
+ "@types/node": "^20.14.11",
28
29
  "changelogen": "^0.5.5",
29
- "tsc-multi": "^1.1.0"
30
+ "rollup": "^4.19.0",
31
+ "rollup-plugin-delete": "^2.0.0",
32
+ "rollup-plugin-node-externals": "^7.1.2"
30
33
  },
31
34
  "keywords": [
35
+ "Decimal128",
36
+ "json",
37
+ "mongo",
32
38
  "mongoose",
33
- "mongoose-plugins",
34
- "mongoose-types",
35
- "mongoose-utils"
39
+ "normalization",
40
+ "pagination",
41
+ "plugin",
42
+ "schema"
36
43
  ],
37
44
  "engines": {
38
45
  "node": ">=18"
39
46
  },
40
47
  "exports": {
41
48
  "./*": {
42
- "default": "./*.mjs",
49
+ "import": "./*.mjs",
50
+ "require": "./*.cjs",
43
51
  "types": "./*.d.ts"
44
52
  },
45
53
  "./plugins/*": {
46
- "default": "./plugins/*.mjs",
54
+ "import": "./plugins/*.mjs",
55
+ "require": "./plugins/*.cjs",
47
56
  "types": "./plugins/*.d.ts"
48
57
  },
49
58
  "./types": {
@@ -0,0 +1,48 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ const lodash = require('lodash');
6
+
7
+ /**
8
+ * Mongoose plugin to normalize the JSON output of documents.
9
+ *
10
+ * This plugin modifies the `toJSON` method of Mongoose schemas to:
11
+ * - Add an `id` field equal to the string representation of `_id`
12
+ * - Remove the `_id` field
13
+ * - Exclude fields marked as `private` from the JSON output
14
+ * - Convert `Decimal128` fields to strings
15
+ * - Remove the `__v` version key
16
+ *
17
+ * @template S - The type of the schema.
18
+ *
19
+ * @param schema - The Mongoose schema to apply the plugin to.
20
+ */
21
+ const mongooseNormalizePlugin = (schema) => {
22
+ const toJSON = schema.get('toJSON');
23
+ const toJSONTransform = toJSON?.transform;
24
+ schema.set('toJSON', {
25
+ ...toJSON,
26
+ transform(doc, ret, options) {
27
+ const copiedRet = { ...ret };
28
+ copiedRet.id = copiedRet._id?.toHexString();
29
+ delete copiedRet._id;
30
+ for (const path in schema.paths) {
31
+ if (schema.paths[path]?.options?.private)
32
+ lodash.unset(copiedRet, path);
33
+ if (schema.paths[path]?.instance === 'Decimal128') {
34
+ const value = lodash.get(copiedRet, path);
35
+ if (value)
36
+ lodash.set(copiedRet, path, value.toString());
37
+ }
38
+ }
39
+ delete copiedRet.__v;
40
+ if (toJSONTransform && typeof toJSONTransform !== 'boolean')
41
+ return toJSONTransform(doc, copiedRet, options);
42
+ return copiedRet;
43
+ }
44
+ });
45
+ };
46
+
47
+ exports.default = mongooseNormalizePlugin;
48
+ exports.mongooseNormalizePlugin = mongooseNormalizePlugin;
@@ -1,4 +1,5 @@
1
- import { get as lodashGet, set as lodashSet, unset as lodashUnset } from 'lodash-es';
1
+ import { unset, get, set } from 'lodash';
2
+
2
3
  /**
3
4
  * Mongoose plugin to normalize the JSON output of documents.
4
5
  *
@@ -13,7 +14,7 @@ import { get as lodashGet, set as lodashSet, unset as lodashUnset } from 'lodash
13
14
  *
14
15
  * @param schema - The Mongoose schema to apply the plugin to.
15
16
  */
16
- export const mongooseNormalizePlugin = (schema) => {
17
+ const mongooseNormalizePlugin = (schema) => {
17
18
  const toJSON = schema.get('toJSON');
18
19
  const toJSONTransform = toJSON?.transform;
19
20
  schema.set('toJSON', {
@@ -24,11 +25,11 @@ export const mongooseNormalizePlugin = (schema) => {
24
25
  delete copiedRet._id;
25
26
  for (const path in schema.paths) {
26
27
  if (schema.paths[path]?.options?.private)
27
- lodashUnset(copiedRet, path);
28
+ unset(copiedRet, path);
28
29
  if (schema.paths[path]?.instance === 'Decimal128') {
29
- const value = lodashGet(copiedRet, path);
30
+ const value = get(copiedRet, path);
30
31
  if (value)
31
- lodashSet(copiedRet, path, value.toString());
32
+ set(copiedRet, path, value.toString());
32
33
  }
33
34
  }
34
35
  delete copiedRet.__v;
@@ -38,4 +39,5 @@ export const mongooseNormalizePlugin = (schema) => {
38
39
  }
39
40
  });
40
41
  };
41
- export default mongooseNormalizePlugin;
42
+
43
+ export { mongooseNormalizePlugin as default, mongooseNormalizePlugin };
package/utils.cjs ADDED
@@ -0,0 +1,263 @@
1
+ 'use strict';
2
+
3
+ const Decimal = require('decimal.js');
4
+ const lodash = require('lodash');
5
+ const mongoose = require('mongoose');
6
+ const mongooseAggregatePaginate = require('mongoose-aggregate-paginate-v2');
7
+ const mongoosePaginate = require('mongoose-paginate-v2');
8
+ const constants = require('./constants.cjs');
9
+ const normalize = require('./plugins/normalize.cjs');
10
+
11
+ const _interopDefaultCompat = e => e && typeof e === 'object' && 'default' in e ? e.default : e;
12
+
13
+ const Decimal__default = /*#__PURE__*/_interopDefaultCompat(Decimal);
14
+ const mongoose__default = /*#__PURE__*/_interopDefaultCompat(mongoose);
15
+ const mongooseAggregatePaginate__default = /*#__PURE__*/_interopDefaultCompat(mongooseAggregatePaginate);
16
+ const mongoosePaginate__default = /*#__PURE__*/_interopDefaultCompat(mongoosePaginate);
17
+
18
+ /**
19
+ * Builds and returns a Mongoose model with specified schema and options.
20
+ *
21
+ * This function sets up a Mongoose model with optional plugins and timestamp settings.
22
+ * It can optionally use a specified connection or the default connection.
23
+ *
24
+ * Determine the connection to use:
25
+ * 1. Use the connection provided in the options, if available.
26
+ * 2. Otherwise, use the default connection stored in `mongooseConnections`.
27
+ * 3. If there's no default connection, create one using the MongoDB URI from the environment variables,
28
+ * or fallback to a local MongoDB instance.
29
+ *
30
+ * @template DocType - The type of the document.
31
+ * @template Model - The type of the model, which extends `BaseMongoosePaginateModel`.
32
+ * @template InstanceMethodsAndOverrides - The type for instance methods and overrides.
33
+ * @template QueryHelpers - The type for additional query helpers.
34
+ *
35
+ * @param collection - The name of the collection.
36
+ * @param name - The name of the model.
37
+ * @param schema - The Mongoose schema to use for the model.
38
+ * @param options - Optional settings for building the model.
39
+ *
40
+ * @returns The created Mongoose model.
41
+ */
42
+ function buildMongooseModel(collection, name, schema, options) {
43
+ if (options?.enableNormalizePlugin !== false)
44
+ schema.plugin(normalize.mongooseNormalizePlugin);
45
+ schema.plugin(mongooseAggregatePaginate__default);
46
+ schema.plugin(mongoosePaginate__default);
47
+ schema.set('timestamps', options?.timestamps === undefined ? true : options.timestamps);
48
+ return (options?.connection || constants.mongooseConnections.default || (constants.mongooseConnections.default = mongoose__default.createConnection(process.env.MONGODB_URI || 'mongodb://localhost:27017'))).model(name, schema, collection);
49
+ }
50
+ /**
51
+ * Creates common Mongoose schema definitions with optional custom schemas and settings.
52
+ *
53
+ * This function generates a set of commonly used schema definitions, such as boolean,
54
+ * number, objectId, and string schemas, with optional custom configurations and rounding
55
+ * options for Decimal128 fields.
56
+ *
57
+ * @template T - The type for custom schemas.
58
+ *
59
+ * @param customSchemas - Optional custom schemas to merge with the common schemas.
60
+ * @param options - Optional settings for creating the common schemas.
61
+ *
62
+ * @returns The merged common and custom schemas.
63
+ */
64
+ function createCommonMongooseSchemas(customSchemas, options) {
65
+ const autoRoundAndToFixedDecimal128Places = options?.autoRoundAndToFixedDecimal128?.places || 2;
66
+ const autoRoundAndToFixedDecimal128Rounding = options?.autoRoundAndToFixedDecimal128?.rounding || Decimal__default.ROUND_DOWN;
67
+ const baseAutoRoundAndToFixedDecimal128 = {
68
+ set: (value) => new Decimal__default(value.toString()).toFixed(autoRoundAndToFixedDecimal128Places, autoRoundAndToFixedDecimal128Rounding),
69
+ type: mongoose__default.Schema.Types.Decimal128
70
+ };
71
+ const baseRequiredBoolean = { required: true, type: Boolean };
72
+ const baseRequiredNumber = { required: true, type: Number };
73
+ const baseRequiredObjectId = { required: true, type: mongoose__default.Schema.Types.ObjectId };
74
+ return lodash.merge({
75
+ boolean: {
76
+ defaultFalse: {
77
+ nonRequired: { default: false, type: Boolean },
78
+ required: { ...baseRequiredBoolean, default: false }
79
+ },
80
+ defaultTrue: {
81
+ nonRequired: { default: true, type: Boolean },
82
+ required: { ...baseRequiredBoolean, default: true }
83
+ },
84
+ nonRequired: { type: Boolean },
85
+ required: baseRequiredBoolean
86
+ },
87
+ decimal128: {
88
+ autoRoundAndToFixed: {
89
+ nonRequired: baseAutoRoundAndToFixedDecimal128,
90
+ required: { ...baseAutoRoundAndToFixedDecimal128, required: true }
91
+ },
92
+ nonRequired: { type: mongoose__default.Schema.Types.Decimal128 },
93
+ required: { required: true, type: mongoose__default.Schema.Types.Decimal128 }
94
+ },
95
+ number: {
96
+ nonRequired: { type: Number },
97
+ required: baseRequiredNumber,
98
+ unique: {
99
+ nonRequired: { type: Number, unique: true },
100
+ required: { ...baseRequiredNumber, unique: true }
101
+ }
102
+ },
103
+ objectId: {
104
+ nonRequired: { type: mongoose__default.Schema.Types.ObjectId },
105
+ required: baseRequiredObjectId,
106
+ unique: {
107
+ nonRequired: { type: mongoose__default.Schema.Types.ObjectId, unique: true },
108
+ required: { ...baseRequiredObjectId, unique: true }
109
+ }
110
+ },
111
+ string: {
112
+ nonRequired: createMongooseStringSchema(),
113
+ private: {
114
+ nonRequired: createMongooseStringSchema('private'),
115
+ required: createMongooseStringSchema('private', 'required'),
116
+ short: {
117
+ nonRequired: createMongooseStringSchema('private', 'short'),
118
+ required: createMongooseStringSchema('private', 'required', 'short'),
119
+ trimmed: {
120
+ nonRequired: createMongooseStringSchema('private', 'short', 'trim'),
121
+ required: createMongooseStringSchema('private', 'required', 'short', 'trim'),
122
+ unique: {
123
+ nonRequired: createMongooseStringSchema('private', 'short', 'trim', 'unique'),
124
+ required: createMongooseStringSchema('private', 'required', 'short', 'trim', 'unique')
125
+ }
126
+ },
127
+ unique: {
128
+ nonRequired: createMongooseStringSchema('private', 'short', 'unique'),
129
+ required: createMongooseStringSchema('private', 'required', 'short', 'unique')
130
+ }
131
+ },
132
+ trimmed: {
133
+ nonRequired: createMongooseStringSchema('private', 'trim'),
134
+ required: createMongooseStringSchema('private', 'required', 'trim'),
135
+ unique: {
136
+ nonRequired: createMongooseStringSchema('private', 'trim', 'unique'),
137
+ required: createMongooseStringSchema('private', 'required', 'trim', 'unique')
138
+ }
139
+ },
140
+ unique: {
141
+ nonRequired: createMongooseStringSchema('private', 'unique'),
142
+ required: createMongooseStringSchema('private', 'required', 'unique')
143
+ }
144
+ },
145
+ required: createMongooseStringSchema('required'),
146
+ short: {
147
+ nonRequired: createMongooseStringSchema('short'),
148
+ required: createMongooseStringSchema('required', 'short'),
149
+ trimmed: {
150
+ nonRequired: createMongooseStringSchema('short', 'trim'),
151
+ required: createMongooseStringSchema('required', 'short', 'trim'),
152
+ unique: {
153
+ nonRequired: createMongooseStringSchema('short', 'trim', 'unique'),
154
+ required: createMongooseStringSchema('required', 'short', 'trim', 'unique')
155
+ }
156
+ },
157
+ unique: {
158
+ nonRequired: createMongooseStringSchema('short', 'unique'),
159
+ required: createMongooseStringSchema('required', 'short', 'unique')
160
+ }
161
+ },
162
+ trimmed: {
163
+ nonRequired: createMongooseStringSchema('trim'),
164
+ required: createMongooseStringSchema('required', 'trim'),
165
+ unique: {
166
+ nonRequired: createMongooseStringSchema('trim', 'unique'),
167
+ required: createMongooseStringSchema('required', 'trim', 'unique')
168
+ }
169
+ },
170
+ unique: {
171
+ nonRequired: createMongooseStringSchema('unique'),
172
+ required: createMongooseStringSchema('required', 'unique')
173
+ }
174
+ }
175
+ }, customSchemas);
176
+ }
177
+ /**
178
+ * Creates a Mongoose schema definition for an ObjectId reference with specified attributes.
179
+ *
180
+ * This function generates a schema definition for an ObjectId reference field, including
181
+ * attributes such as 'private', 'required', and 'unique'.
182
+ *
183
+ * @template R - The type of the reference model name.
184
+ * @template T - An array of attributes to apply to the schema field.
185
+ *
186
+ * @param refModelName - The name of the reference model.
187
+ * @param attributes - The attributes to apply to the schema field.
188
+ *
189
+ * @returns The generated ObjectId reference schema definition.
190
+ */
191
+ function createMongooseObjectIdRefSchema(refModelName, ...attributes) {
192
+ const schema = { ref: refModelName, type: mongoose__default.Schema.Types.ObjectId };
193
+ new Set(attributes).forEach((attribute) => (schema[attribute] = true));
194
+ return schema;
195
+ }
196
+ /**
197
+ * Creates a Mongoose schema definition for a string field with specified attributes.
198
+ *
199
+ * This function generates a schema definition for a string field, including attributes
200
+ * such as 'private', 'required', 'short', 'trim', and 'unique'. If the 'short' attribute
201
+ * is included, the `maxlength` is set to 16.
202
+ *
203
+ * @template T - An array of attributes to apply to the schema field.
204
+ *
205
+ * @param attributes - The attributes to apply to the schema field.
206
+ *
207
+ * @returns The generated string schema definition.
208
+ */
209
+ function createMongooseStringSchema(...attributes) {
210
+ const schema = { type: String };
211
+ new Set(attributes).forEach((attribute) => {
212
+ if (attribute === 'short')
213
+ return (schema.maxlength = 16);
214
+ schema[attribute] = true;
215
+ });
216
+ return schema;
217
+ }
218
+ /**
219
+ * Converts a document or ObjectId to a document using the specified model.
220
+ *
221
+ * This function takes a document or ObjectId and returns the corresponding document
222
+ * from the database using the specified model. Optionally, specific fields can be selected.
223
+ *
224
+ * @template D - The type of the hydrated document.
225
+ * @template DocType - The type of the document.
226
+ * @template InstanceMethodsAndOverrides - The type for instance methods and overrides.
227
+ * @template QueryHelpers - The type for additional query helpers.
228
+ *
229
+ * @param documentOrObjectId - The document or ObjectId to convert.
230
+ * @param model - The Mongoose model to use for the conversion.
231
+ * @param selectFields - Optional fields to select from the document.
232
+ *
233
+ * @returns The corresponding document or null if not found.
234
+ */
235
+ async function mongooseDocumentOrObjectIdToDocument(documentOrObjectId, model, selectFields) {
236
+ if (typeof documentOrObjectId === 'string' || documentOrObjectId instanceof mongoose.Types.ObjectId)
237
+ return (await model.findById(documentOrObjectId).select(selectFields || []));
238
+ return documentOrObjectId;
239
+ }
240
+ /**
241
+ * Sets up a getter to convert Decimal128 fields to strings in a Mongoose schema.
242
+ *
243
+ * This function adds a getter to the specified Decimal128 fields in the schema,
244
+ * converting the values to strings for easier use.
245
+ *
246
+ * @template DocType - The type of the document.
247
+ * @template Model - The type of the model, which extends `BaseMongoosePaginateModel`.
248
+ * @template InstanceMethodsAndOverrides - The type for instance methods and overrides.
249
+ * @template QueryHelpers - The type for additional query helpers.
250
+ *
251
+ * @param schema - The Mongoose schema to modify.
252
+ * @param fields - The Decimal128 fields to add the getter to.
253
+ */
254
+ function setupDecimal128FieldsToStringGetter(schema, ...fields) {
255
+ fields.forEach((field) => schema.path(field).get((value) => value?.toString()));
256
+ }
257
+
258
+ exports.buildMongooseModel = buildMongooseModel;
259
+ exports.createCommonMongooseSchemas = createCommonMongooseSchemas;
260
+ exports.createMongooseObjectIdRefSchema = createMongooseObjectIdRefSchema;
261
+ exports.createMongooseStringSchema = createMongooseStringSchema;
262
+ exports.mongooseDocumentOrObjectIdToDocument = mongooseDocumentOrObjectIdToDocument;
263
+ exports.setupDecimal128FieldsToStringGetter = setupDecimal128FieldsToStringGetter;
package/utils.mjs CHANGED
@@ -1,11 +1,11 @@
1
1
  import Decimal from 'decimal.js';
2
- import { merge } from 'lodash-es';
3
- import mongoose from 'mongoose';
4
- import { Types } from 'mongoose';
2
+ import { merge } from 'lodash';
3
+ import mongoose, { Types } from 'mongoose';
5
4
  import mongooseAggregatePaginate from 'mongoose-aggregate-paginate-v2';
6
5
  import mongoosePaginate from 'mongoose-paginate-v2';
7
- import { mongooseConnections } from "./constants.mjs";
8
- import mongooseNormalizePlugin from "./plugins/normalize.mjs";
6
+ import { mongooseConnections } from './constants.mjs';
7
+ import { mongooseNormalizePlugin } from './plugins/normalize.mjs';
8
+
9
9
  /**
10
10
  * Builds and returns a Mongoose model with specified schema and options.
11
11
  *
@@ -30,7 +30,7 @@ import mongooseNormalizePlugin from "./plugins/normalize.mjs";
30
30
  *
31
31
  * @returns The created Mongoose model.
32
32
  */
33
- export function buildMongooseModel(collection, name, schema, options) {
33
+ function buildMongooseModel(collection, name, schema, options) {
34
34
  if (options?.enableNormalizePlugin !== false)
35
35
  schema.plugin(mongooseNormalizePlugin);
36
36
  schema.plugin(mongooseAggregatePaginate);
@@ -52,7 +52,7 @@ export function buildMongooseModel(collection, name, schema, options) {
52
52
  *
53
53
  * @returns The merged common and custom schemas.
54
54
  */
55
- export function createCommonMongooseSchemas(customSchemas, options) {
55
+ function createCommonMongooseSchemas(customSchemas, options) {
56
56
  const autoRoundAndToFixedDecimal128Places = options?.autoRoundAndToFixedDecimal128?.places || 2;
57
57
  const autoRoundAndToFixedDecimal128Rounding = options?.autoRoundAndToFixedDecimal128?.rounding || Decimal.ROUND_DOWN;
58
58
  const baseAutoRoundAndToFixedDecimal128 = {
@@ -179,7 +179,7 @@ export function createCommonMongooseSchemas(customSchemas, options) {
179
179
  *
180
180
  * @returns The generated ObjectId reference schema definition.
181
181
  */
182
- export function createMongooseObjectIdRefSchema(refModelName, ...attributes) {
182
+ function createMongooseObjectIdRefSchema(refModelName, ...attributes) {
183
183
  const schema = { ref: refModelName, type: mongoose.Schema.Types.ObjectId };
184
184
  new Set(attributes).forEach((attribute) => (schema[attribute] = true));
185
185
  return schema;
@@ -197,7 +197,7 @@ export function createMongooseObjectIdRefSchema(refModelName, ...attributes) {
197
197
  *
198
198
  * @returns The generated string schema definition.
199
199
  */
200
- export function createMongooseStringSchema(...attributes) {
200
+ function createMongooseStringSchema(...attributes) {
201
201
  const schema = { type: String };
202
202
  new Set(attributes).forEach((attribute) => {
203
203
  if (attribute === 'short')
@@ -223,7 +223,7 @@ export function createMongooseStringSchema(...attributes) {
223
223
  *
224
224
  * @returns The corresponding document or null if not found.
225
225
  */
226
- export async function mongooseDocumentOrObjectIdToDocument(documentOrObjectId, model, selectFields) {
226
+ async function mongooseDocumentOrObjectIdToDocument(documentOrObjectId, model, selectFields) {
227
227
  if (typeof documentOrObjectId === 'string' || documentOrObjectId instanceof Types.ObjectId)
228
228
  return (await model.findById(documentOrObjectId).select(selectFields || []));
229
229
  return documentOrObjectId;
@@ -242,6 +242,8 @@ export async function mongooseDocumentOrObjectIdToDocument(documentOrObjectId, m
242
242
  * @param schema - The Mongoose schema to modify.
243
243
  * @param fields - The Decimal128 fields to add the getter to.
244
244
  */
245
- export function setupDecimal128FieldsToStringGetter(schema, ...fields) {
245
+ function setupDecimal128FieldsToStringGetter(schema, ...fields) {
246
246
  fields.forEach((field) => schema.path(field).get((value) => value?.toString()));
247
247
  }
248
+
249
+ export { buildMongooseModel, createCommonMongooseSchemas, createMongooseObjectIdRefSchema, createMongooseStringSchema, mongooseDocumentOrObjectIdToDocument, setupDecimal128FieldsToStringGetter };
@@ -1,7 +0,0 @@
1
- //
2
- // Based on type declarations for mongoose-paginate-v2 1.3.
3
- //
4
- // Thanks to knyuwork <https://github.com/knyuwork>
5
- // and LiRen Tu <https://github.com/tuliren> for their contribution
6
- // Used with mongoose-paginate, redefined and renamed here to avoid conflicts.
7
- export default mongooseAggregatePaginate;
package/types/data.mjs DELETED
@@ -1 +0,0 @@
1
- export {};
package/types/index.mjs DELETED
@@ -1 +0,0 @@
1
- export {};
package/types/options.mjs DELETED
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export default _;
package/types/schema.mjs DELETED
@@ -1 +0,0 @@
1
- export {};