mongoose-utility-kit 0.0.1 → 0.2.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/.eslintignore ADDED
@@ -0,0 +1 @@
1
+ dist
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # mongoose-utility-kit
2
2
 
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 9217086: fixed ToMapQueryHelpers & ToRecordsQueryHelpers interfaces
8
+
9
+ ## 0.1.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 9bd9c4c: Added "toMap" and "toRecords" plugins. Added type "ExtractDocType".
14
+
3
15
  ## 0.0.1
4
16
 
5
17
  ### Patch Changes
package/README.md CHANGED
@@ -1,16 +1,21 @@
1
1
  # mongoose-utility-kit 🛠️
2
2
 
3
- Utility functions to simplify common `mongoose` operations. Designed for `TypeScript` and `mongoose` projects with strict type safety.
3
+ A set of utility functions and plugins to simplify common `mongoose` operations. Designed for `TypeScript` and `mongoose` projects with strict type safety.
4
+
5
+ [![npm](https://nodei.co/npm/mongoose-utility-kit.png)](https://www.npmjs.com/package/mongoose-utility-kit)
4
6
 
5
7
  ## Features
6
8
 
7
9
  - **Type-safe**: Built with TypeScript for robust type checking.
8
- - **Efficient**: Reduces redundant database queries.
10
+ - **Efficient**: Reduces redundant database queries and simplifies data transformations.
9
11
  - **Flexible**: Handles both document instances and ObjectIds seamlessly.
10
12
  - **Population Ready**: Designed for mongoose documents with populated references.
13
+ - **Data Transformation**: Provides plugins to convert query results into `Map` or `Record` objects.
11
14
 
12
15
  ## Installation
13
16
 
17
+ [mongoose](https://www.npmjs.com/package/mongoose) >=8 is required as peer dependency
18
+
14
19
  ```sh
15
20
  npm install mongoose-utility-kit
16
21
  ```
@@ -26,6 +31,7 @@ yarn add mongoose-utility-kit
26
31
  These helpers are designed for mongoose projects using TypeScript with proper document typing. For best results:
27
32
 
28
33
  1. Define your hydrated document types using mongoose's `HydratedDocument`:
34
+
29
35
  ```ts
30
36
  // user.ts
31
37
  import { HydratedDocument } from 'mongoose';
@@ -43,10 +49,11 @@ export type UserHydratedDocument = HydratedDocument<IUser, IUserDocumentOverride
43
49
  ```
44
50
 
45
51
  2. Use `PopulatedDoc` for population references:
52
+
46
53
  ```ts
47
54
  // comment.ts
48
- import { Types, PopulatedDoc } from 'mongoose';
49
- import { UserHydratedDocument } from './user';
55
+ import { Types, PopulatedDoc } from "mongoose";
56
+ import { UserHydratedDocument } from "./user";
50
57
 
51
58
  export interface IComment {
52
59
  user: PopulatedDoc<UserHydratedDocument>;
@@ -56,78 +63,141 @@ export interface IComment {
56
63
 
57
64
  ## Usage
58
65
 
59
- ### 1. `getPopulatedDocumentId`
66
+ ### Utility Functions
67
+
68
+ #### 1. `getPopulatedDocumentId`
69
+
60
70
  Handle both populated documents and ObjectIds safely:
71
+
61
72
  ```ts
62
- import { getPopulatedDocumentId } from 'mongoose-utility-kit';
73
+ import { getPopulatedDocumentId } from "mongoose-utility-kit";
63
74
 
64
75
  // With ObjectId reference
65
- const comment = await Comment
66
- .findById(someId)
67
- .orFail();
68
- getPopulatedDocumentId(comment.user); // "507f191e810c19729de860ea"
76
+ const comment = await Comment.findById(someId).orFail();
77
+ getPopulatedDocumentId(comment.user); // '507f191e810c19729de860ea'
69
78
 
70
79
  // With populated document
71
- const comment = await Comment
72
- .findById(someId)
73
- .populate<{ user: UserHydratedDocument }>('user')
80
+ const comment = await Comment.findById(someId)
81
+ .populate<{ user: UserHydratedDocument }>("user")
74
82
  .orFail();
75
- getPopulatedDocumentId(comment.user); // "507f191e810c19729de860ea"
83
+ getPopulatedDocumentId(comment.user); // '507f191e810c19729de860ea'
76
84
  ```
77
85
 
78
- ### 2. `findOrReturnInstance`
86
+ #### 2. `findOrReturnInstance`
87
+
79
88
  ```ts
89
+ import { findOrReturnInstance } from "mongoose-utility-kit";
90
+
80
91
  // With ObjectId reference
81
- const comment = await Comment
82
- .findById(someId)
83
- .orFail();
92
+ const comment = await Comment.findById(someId).orFail();
84
93
  findOrReturnInstance(comment.user, UserModel);
85
94
 
86
95
  // With populated document
87
- const comment = await Comment
88
- .findById(someId)
89
- .populate<{ user: UserHydratedDocument }>('user')
96
+ const comment = await Comment.findById(someId)
97
+ .populate<{ user: UserHydratedDocument }>("user")
90
98
  .orFail();
91
99
  findOrReturnInstance(comment.user, UserModel);
92
100
  ```
93
101
 
94
- ### 3. `findOrReturnManyInstances`
102
+ #### 3. `findOrReturnManyInstances`
103
+
95
104
  ```ts
105
+ import { findOrReturnManyInstances } from "mongoose-utility-kit";
106
+ import { UserHydratedDocument } from "./user";
107
+ import { Types } from "mongoose";
108
+
96
109
  const inputs: (UserHydratedDocument | Types.ObjectId)[] = [
97
110
  existingUserDocument,
98
- new Types.ObjectId()
111
+ new Types.ObjectId(),
99
112
  ];
100
113
 
101
114
  const users = await findOrReturnManyInstances(inputs, UserModel);
102
115
  ```
103
116
 
117
+ ### Mongoose Plugins
118
+
119
+ These plugins provide helper methods for Mongoose queries to transform the results into `Map` or `Record` objects (standard JavaScript objects), using the documents' `_id` as the key.
120
+
121
+ #### Details
122
+
123
+ - **toMap()**: Returns a `Map` where the key is a string representing the `_id` of each document and the value is the document itself.
124
+ - **toRecords()**: Returns a `Record` (a standard JavaScript object) where the key is a string representing the `_id` of each document and the value is the document itself.
125
+
126
+ #### Integration
127
+
128
+ 1. Import the plugins:
129
+
130
+ ```ts
131
+ import { toMap, toRecords } from "mongoose-utility-kit";
132
+ ```
133
+
134
+ 2. Register the plugins with your schema:
135
+
136
+ ```ts
137
+ type MyModelHydratedDocument = HydratedDocument<IMyModel>;
138
+
139
+ type MyModelType = Model<
140
+ IMyModel,
141
+ ToMapQueryHelpers<IMyModel, MyModelHydratedDocument> & ToRecordsQueryHelpers<IMyModel, MyModelHydratedDocument>,
142
+ {},
143
+ {},
144
+ MyModelHydratedDocument
145
+ >;
146
+
147
+ const schema = new mongoose.Schema<IMyModel, MyModelType>({
148
+ // Define your schema here
149
+ name: String,
150
+ value: Number,
151
+ });
152
+
153
+ schema.plugin(toMap);
154
+ schema.plugin(toRecords);
155
+
156
+ const MyModel = mongoose.model<IMyModel, MyModelType>("MyModel", schema);
157
+ ```
158
+
159
+ #### Examples
160
+
161
+ ```ts
162
+ // Converts the query result to a Map
163
+ const myMap = await MyModel.find({}).toMap(); // new Map<string, MyModel>
164
+
165
+ // Converts the query result to a Record
166
+ const myRecords = await MyModel.find({}).toRecords(); // Record<string, MyModel>
167
+ ```
168
+
104
169
  ## API Documentation
105
170
 
106
171
  ### `getPopulatedDocumentId`
172
+
107
173
  ```ts
108
174
  function getPopulatedDocumentId<HydratedDocType extends Document>(
109
175
  populatedDocument: PopulatedDoc<HydratedDocType>
110
- ): string
176
+ ): string;
111
177
  ```
178
+
112
179
  **Handles:** Both populated documents and raw ObjectIds
113
180
  **Throws:** If no valid ID found (`Error('document incorrect')`)
114
181
 
115
182
  ### `findOrReturnInstance`
183
+
116
184
  ```ts
117
185
  async function findOrReturnInstance<HydratedDocType extends Document>(
118
186
  docOrId: HydratedDocType | Types.ObjectId,
119
187
  MongooseModel: Model<any, any, any, any, HydratedDocType>,
120
188
  err?: Error | (() => Error)
121
- ): Promise<HydratedDocType>
189
+ ): Promise<HydratedDocType>;
122
190
  ```
191
+
123
192
  **Throws:** Default error or custom error if document not found
124
193
 
125
194
  ### `findOrReturnManyInstances`
195
+
126
196
  ```ts
127
197
  async function findOrReturnManyInstances<HydratedDocType extends Document>(
128
198
  docOrIds: (HydratedDocType | Types.ObjectId)[],
129
199
  MongooseModel: Model<any, any, any, any, HydratedDocType>
130
- ): Promise<HydratedDocType[]>
200
+ ): Promise<HydratedDocType[]>;
131
201
  ```
132
202
 
133
203
  ## Development
@@ -135,12 +205,15 @@ async function findOrReturnManyInstances<HydratedDocType extends Document>(
135
205
  ```sh
136
206
  yarn test
137
207
  ```
208
+
138
209
  Tests use `mongodb-memory-server` for in-memory MongoDB testing.
139
210
 
140
211
  ## Compatibility
141
- - mongoose 6.x+
212
+
213
+ - mongoose 8.x+
142
214
  - TypeScript 4.5+
143
215
  - Node.js 16+
144
216
 
145
217
  ## License
218
+
146
219
  MIT
package/dist/index.cjs CHANGED
@@ -22,10 +22,48 @@ var index_exports = {};
22
22
  __export(index_exports, {
23
23
  findOrReturnInstance: () => findOrReturnInstance,
24
24
  findOrReturnManyInstances: () => findOrReturnManyInstances,
25
- getPopulatedDocumentId: () => getPopulatedDocumentId
25
+ getPopulatedDocumentId: () => getPopulatedDocumentId,
26
+ toMap: () => toMap_default,
27
+ toRecords: () => toRecords_default
26
28
  });
27
29
  module.exports = __toCommonJS(index_exports);
28
30
 
31
+ // src/plugins/toMap.ts
32
+ var toMapPlugin = (schema) => {
33
+ schema.query.toMap = function() {
34
+ const result = this.transform((docs) => {
35
+ if (!docs) {
36
+ return /* @__PURE__ */ new Map();
37
+ }
38
+ if (Array.isArray(docs)) {
39
+ return new Map(docs.map((doc) => [doc._id.toString(), doc]));
40
+ }
41
+ return /* @__PURE__ */ new Map([[docs._id.toString(), docs]]);
42
+ });
43
+ return result;
44
+ };
45
+ };
46
+ var toMap_default = toMapPlugin;
47
+
48
+ // src/plugins/toRecords.ts
49
+ var toRecordsPlugin = (schema) => {
50
+ schema.query.toRecords = function toRecords() {
51
+ const result = this.transform((docs) => {
52
+ if (!docs) {
53
+ return {};
54
+ }
55
+ if (Array.isArray(docs)) {
56
+ return Object.fromEntries(docs.map((doc) => [doc._id.toString(), doc]));
57
+ }
58
+ return {
59
+ [docs._id.toString()]: docs
60
+ };
61
+ });
62
+ return result;
63
+ };
64
+ };
65
+ var toRecords_default = toRecordsPlugin;
66
+
29
67
  // src/populated/functions.ts
30
68
  var import_mongoose = require("mongoose");
31
69
  var getPopulatedDocumentId = (populatedDocument) => {
@@ -68,5 +106,7 @@ var findOrReturnManyInstances = async (docOrIds, MongooseModel) => {
68
106
  0 && (module.exports = {
69
107
  findOrReturnInstance,
70
108
  findOrReturnManyInstances,
71
- getPopulatedDocumentId
109
+ getPopulatedDocumentId,
110
+ toMap,
111
+ toRecords
72
112
  });
package/dist/index.d.cts CHANGED
@@ -1,4 +1,109 @@
1
- import { Document, PopulatedDoc, Types, Model } from 'mongoose';
1
+ import { HydratedDocument, Schema, QueryWithHelpers, Document, PopulatedDoc, Types, Model } from 'mongoose';
2
+
3
+ /**
4
+ * Extracts the underlying document type from a Mongoose `HydratedDocument`.
5
+ * This utility type is useful for working with Mongoose models and their hydrated versions.
6
+ *
7
+ * @template T The type of the `HydratedDocument`.
8
+ * @returns The type of the document if `T` is a `HydratedDocument`, otherwise `never`.
9
+ */
10
+ type ExtractDocType<T> = T extends HydratedDocument<infer U> ? U : never;
11
+
12
+ /**
13
+ * Interface for query helpers that support converting results to a `Map`.
14
+ *
15
+ * @template T The type of the `HydratedDocument`.
16
+ */
17
+ interface ToMapQueryHelpers<RawDocType, HydratedDocType> {
18
+ /**
19
+ * Query helper interface for converting query results into a `Map` keyed by string.
20
+ *
21
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
22
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
23
+ *
24
+ * @remarks
25
+ * - The `toMap` method transforms an array of documents returned by a query into a `Map<string, T>`,
26
+ * where the key is typically derived from a document property (e.g., `_id` as a string).
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * const docsMap = await Model.find().toMap();
31
+ * // docsMap is a Map<string, HydratedDocType>
32
+ * ```
33
+ */
34
+ toMap(this: QueryWithHelpers<HydratedDocType[], HydratedDocType>): QueryWithHelpers<Map<string, HydratedDocType>, HydratedDocType>;
35
+ /**
36
+ * Query helper interface for converting query results into a `Map` keyed by string.
37
+ *
38
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
39
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
40
+ *
41
+ * @remarks
42
+ * - The `toMap` method transforms an array of documents returned by a query into a `Map<string, T>`,
43
+ * where the key is typically derived from a document property (e.g., `_id` as a string).
44
+ *
45
+ * @example
46
+ * ```typescript
47
+ * const docsMap = await Model.find().toMap();
48
+ * // docsMap is a Map<string, RawDocType>
49
+ * ```
50
+ */
51
+ toMap(this: QueryWithHelpers<RawDocType[], HydratedDocType>): QueryWithHelpers<Map<string, RawDocType>, HydratedDocType>;
52
+ }
53
+ /**
54
+ * Mongoose plugin to add the `toMap` method to queries.
55
+ *
56
+ * @template T The type of the `HydratedDocument`.
57
+ * @param schema The Mongoose schema to extend.
58
+ */
59
+ declare const toMapPlugin: <T extends unknown>(schema: Schema<any, any, any, ToMapQueryHelpers<ExtractDocType<T>, T>, any, any, any>) => void;
60
+
61
+ /**
62
+ * Interface for query helpers that support converting results to a record (object).
63
+ *
64
+ * @template T The type of the `HydratedDocument`.
65
+ */
66
+ interface ToRecordsQueryHelpers<RawDocType, HydratedDocType> {
67
+ /**
68
+ * Query helpers for transforming query results into a record (object) keyed by document IDs.
69
+ *
70
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
71
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
72
+ *
73
+ * Provides overloaded `toRecords` methods for use with Mongoose queries, allowing the result
74
+ * array to be converted into a record where each key is the document's `_id` (as a string)
75
+ * and the value is the corresponding document.
76
+ *
77
+ * @example
78
+ * // Usage in a Mongoose query:
79
+ * const records = await Model.find().toRecords();
80
+ * // records is of type Record<string, HydratedDocType>
81
+ */
82
+ toRecords(this: QueryWithHelpers<HydratedDocType[], HydratedDocType>): QueryWithHelpers<Record<string, HydratedDocType>, HydratedDocType>;
83
+ /**
84
+ * Query helpers for transforming query results into a record (object) keyed by document IDs.
85
+ *
86
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
87
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
88
+ *
89
+ * Provides overloaded `toRecords` methods for use with Mongoose queries, allowing the result
90
+ * array to be converted into a record where each key is the document's `_id` (as a string)
91
+ * and the value is the corresponding document.
92
+ *
93
+ * @example
94
+ * // Usage in a Mongoose query:
95
+ * const records = await Model.find().toRecords();
96
+ * // records is of type Record<string, RawDocType>
97
+ */
98
+ toRecords(this: QueryWithHelpers<RawDocType[], HydratedDocType>): QueryWithHelpers<Record<string, RawDocType>, HydratedDocType>;
99
+ }
100
+ /**
101
+ * Mongoose plugin to add the `toRecords` method to queries.
102
+ *
103
+ * @template T The type of the `HydratedDocument`.
104
+ * @param schema The Mongoose schema to extend.
105
+ */
106
+ declare const toRecordsPlugin: <T extends unknown>(schema: Schema<any, any, any, ToRecordsQueryHelpers<ExtractDocType<T>, T>, any, any, any>) => void;
2
107
 
3
108
  /**
4
109
  * Extracts the ID from a populated Mongoose document.
@@ -54,4 +159,4 @@ declare const findOrReturnInstance: <HydratedDocType extends Document>(docOrId:
54
159
  */
55
160
  declare const findOrReturnManyInstances: <HydratedDocType extends Document>(docOrIds: (HydratedDocType | Types.ObjectId)[], MongooseModel: Model<any, any, any, any, HydratedDocType>) => Promise<HydratedDocType[]>;
56
161
 
57
- export { findOrReturnInstance, findOrReturnManyInstances, getPopulatedDocumentId };
162
+ export { type ToMapQueryHelpers, type ToRecordsQueryHelpers, findOrReturnInstance, findOrReturnManyInstances, getPopulatedDocumentId, toMapPlugin as toMap, toRecordsPlugin as toRecords };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,109 @@
1
- import { Document, PopulatedDoc, Types, Model } from 'mongoose';
1
+ import { HydratedDocument, Schema, QueryWithHelpers, Document, PopulatedDoc, Types, Model } from 'mongoose';
2
+
3
+ /**
4
+ * Extracts the underlying document type from a Mongoose `HydratedDocument`.
5
+ * This utility type is useful for working with Mongoose models and their hydrated versions.
6
+ *
7
+ * @template T The type of the `HydratedDocument`.
8
+ * @returns The type of the document if `T` is a `HydratedDocument`, otherwise `never`.
9
+ */
10
+ type ExtractDocType<T> = T extends HydratedDocument<infer U> ? U : never;
11
+
12
+ /**
13
+ * Interface for query helpers that support converting results to a `Map`.
14
+ *
15
+ * @template T The type of the `HydratedDocument`.
16
+ */
17
+ interface ToMapQueryHelpers<RawDocType, HydratedDocType> {
18
+ /**
19
+ * Query helper interface for converting query results into a `Map` keyed by string.
20
+ *
21
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
22
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
23
+ *
24
+ * @remarks
25
+ * - The `toMap` method transforms an array of documents returned by a query into a `Map<string, T>`,
26
+ * where the key is typically derived from a document property (e.g., `_id` as a string).
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * const docsMap = await Model.find().toMap();
31
+ * // docsMap is a Map<string, HydratedDocType>
32
+ * ```
33
+ */
34
+ toMap(this: QueryWithHelpers<HydratedDocType[], HydratedDocType>): QueryWithHelpers<Map<string, HydratedDocType>, HydratedDocType>;
35
+ /**
36
+ * Query helper interface for converting query results into a `Map` keyed by string.
37
+ *
38
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
39
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
40
+ *
41
+ * @remarks
42
+ * - The `toMap` method transforms an array of documents returned by a query into a `Map<string, T>`,
43
+ * where the key is typically derived from a document property (e.g., `_id` as a string).
44
+ *
45
+ * @example
46
+ * ```typescript
47
+ * const docsMap = await Model.find().toMap();
48
+ * // docsMap is a Map<string, RawDocType>
49
+ * ```
50
+ */
51
+ toMap(this: QueryWithHelpers<RawDocType[], HydratedDocType>): QueryWithHelpers<Map<string, RawDocType>, HydratedDocType>;
52
+ }
53
+ /**
54
+ * Mongoose plugin to add the `toMap` method to queries.
55
+ *
56
+ * @template T The type of the `HydratedDocument`.
57
+ * @param schema The Mongoose schema to extend.
58
+ */
59
+ declare const toMapPlugin: <T extends unknown>(schema: Schema<any, any, any, ToMapQueryHelpers<ExtractDocType<T>, T>, any, any, any>) => void;
60
+
61
+ /**
62
+ * Interface for query helpers that support converting results to a record (object).
63
+ *
64
+ * @template T The type of the `HydratedDocument`.
65
+ */
66
+ interface ToRecordsQueryHelpers<RawDocType, HydratedDocType> {
67
+ /**
68
+ * Query helpers for transforming query results into a record (object) keyed by document IDs.
69
+ *
70
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
71
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
72
+ *
73
+ * Provides overloaded `toRecords` methods for use with Mongoose queries, allowing the result
74
+ * array to be converted into a record where each key is the document's `_id` (as a string)
75
+ * and the value is the corresponding document.
76
+ *
77
+ * @example
78
+ * // Usage in a Mongoose query:
79
+ * const records = await Model.find().toRecords();
80
+ * // records is of type Record<string, HydratedDocType>
81
+ */
82
+ toRecords(this: QueryWithHelpers<HydratedDocType[], HydratedDocType>): QueryWithHelpers<Record<string, HydratedDocType>, HydratedDocType>;
83
+ /**
84
+ * Query helpers for transforming query results into a record (object) keyed by document IDs.
85
+ *
86
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
87
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
88
+ *
89
+ * Provides overloaded `toRecords` methods for use with Mongoose queries, allowing the result
90
+ * array to be converted into a record where each key is the document's `_id` (as a string)
91
+ * and the value is the corresponding document.
92
+ *
93
+ * @example
94
+ * // Usage in a Mongoose query:
95
+ * const records = await Model.find().toRecords();
96
+ * // records is of type Record<string, RawDocType>
97
+ */
98
+ toRecords(this: QueryWithHelpers<RawDocType[], HydratedDocType>): QueryWithHelpers<Record<string, RawDocType>, HydratedDocType>;
99
+ }
100
+ /**
101
+ * Mongoose plugin to add the `toRecords` method to queries.
102
+ *
103
+ * @template T The type of the `HydratedDocument`.
104
+ * @param schema The Mongoose schema to extend.
105
+ */
106
+ declare const toRecordsPlugin: <T extends unknown>(schema: Schema<any, any, any, ToRecordsQueryHelpers<ExtractDocType<T>, T>, any, any, any>) => void;
2
107
 
3
108
  /**
4
109
  * Extracts the ID from a populated Mongoose document.
@@ -54,4 +159,4 @@ declare const findOrReturnInstance: <HydratedDocType extends Document>(docOrId:
54
159
  */
55
160
  declare const findOrReturnManyInstances: <HydratedDocType extends Document>(docOrIds: (HydratedDocType | Types.ObjectId)[], MongooseModel: Model<any, any, any, any, HydratedDocType>) => Promise<HydratedDocType[]>;
56
161
 
57
- export { findOrReturnInstance, findOrReturnManyInstances, getPopulatedDocumentId };
162
+ export { type ToMapQueryHelpers, type ToRecordsQueryHelpers, findOrReturnInstance, findOrReturnManyInstances, getPopulatedDocumentId, toMapPlugin as toMap, toRecordsPlugin as toRecords };
package/dist/index.js CHANGED
@@ -1,9 +1,44 @@
1
+ // src/plugins/toMap.ts
2
+ var toMapPlugin = (schema) => {
3
+ schema.query.toMap = function() {
4
+ const result = this.transform((docs) => {
5
+ if (!docs) {
6
+ return /* @__PURE__ */ new Map();
7
+ }
8
+ if (Array.isArray(docs)) {
9
+ return new Map(docs.map((doc) => [doc._id.toString(), doc]));
10
+ }
11
+ return /* @__PURE__ */ new Map([[docs._id.toString(), docs]]);
12
+ });
13
+ return result;
14
+ };
15
+ };
16
+ var toMap_default = toMapPlugin;
17
+
18
+ // src/plugins/toRecords.ts
19
+ var toRecordsPlugin = (schema) => {
20
+ schema.query.toRecords = function toRecords() {
21
+ const result = this.transform((docs) => {
22
+ if (!docs) {
23
+ return {};
24
+ }
25
+ if (Array.isArray(docs)) {
26
+ return Object.fromEntries(docs.map((doc) => [doc._id.toString(), doc]));
27
+ }
28
+ return {
29
+ [docs._id.toString()]: docs
30
+ };
31
+ });
32
+ return result;
33
+ };
34
+ };
35
+ var toRecords_default = toRecordsPlugin;
36
+
1
37
  // src/populated/functions.ts
2
38
  import {
3
- Types,
4
- } from 'mongoose';
5
-
6
- const getPopulatedDocumentId = (populatedDocument) => {
39
+ Types
40
+ } from "mongoose";
41
+ var getPopulatedDocumentId = (populatedDocument) => {
7
42
  if (populatedDocument instanceof Types.ObjectId) {
8
43
  return populatedDocument.toString();
9
44
  }
@@ -11,21 +46,20 @@ const getPopulatedDocumentId = (populatedDocument) => {
11
46
  if (id) {
12
47
  return id.toString();
13
48
  }
14
- throw new Error('document incorrect');
49
+ throw new Error("document incorrect");
15
50
  };
16
- const findOrReturnInstance = async (docOrId, MongooseModel, err) => {
51
+ var findOrReturnInstance = async (docOrId, MongooseModel, err) => {
17
52
  if (docOrId instanceof MongooseModel) {
18
53
  return docOrId;
19
54
  }
20
55
  const result = await MongooseModel.findById(docOrId).orFail(err);
21
56
  return result;
22
57
  };
23
- const findOrReturnManyInstances = async (docOrIds, MongooseModel) => {
58
+ var findOrReturnManyInstances = async (docOrIds, MongooseModel) => {
24
59
  const [result, objectIds] = docOrIds.reduce((acc, docOrId) => {
25
60
  if (docOrId instanceof MongooseModel) {
26
61
  acc[0].push(docOrId);
27
- }
28
- else if (docOrId instanceof Types.ObjectId) {
62
+ } else if (docOrId instanceof Types.ObjectId) {
29
63
  acc[1].push(docOrId);
30
64
  }
31
65
  return acc;
@@ -33,8 +67,8 @@ const findOrReturnManyInstances = async (docOrIds, MongooseModel) => {
33
67
  if (objectIds.length > 0) {
34
68
  const docs = await MongooseModel.find({
35
69
  _id: {
36
- $in: objectIds,
37
- },
70
+ $in: objectIds
71
+ }
38
72
  });
39
73
  result.push(...docs);
40
74
  }
@@ -44,4 +78,6 @@ export {
44
78
  findOrReturnInstance,
45
79
  findOrReturnManyInstances,
46
80
  getPopulatedDocumentId,
81
+ toMap_default as toMap,
82
+ toRecords_default as toRecords
47
83
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mongoose-utility-kit",
3
- "version": "0.0.1",
3
+ "version": "0.2.0",
4
4
  "description": "A set of utility functions for the Mongoose library",
5
5
  "keywords": [
6
6
  "mongoose",
@@ -25,7 +25,7 @@
25
25
  "test": "jest",
26
26
  "build": "tsup",
27
27
  "check-exports": "attw --pack .",
28
- "lint": "eslint --fix .",
28
+ "lint": "eslint --fix . --ext .ts",
29
29
  "ci": "yarn build && yarn check-exports && yarn lint && yarn test",
30
30
  "local-release": "changeset version && changeset publish",
31
31
  "prepublishOnly": "yarn ci"
package/src/index.ts CHANGED
@@ -1 +1,2 @@
1
+ export * from './plugins';
1
2
  export * from './populated';
@@ -0,0 +1,7 @@
1
+ // toMap
2
+ export { default as toMap } from './toMap';
3
+ export type * from './toMap';
4
+
5
+ // toRecords
6
+ export { default as toRecords } from './toRecords';
7
+ export type * from './toRecords';
@@ -0,0 +1,75 @@
1
+ /* eslint-disable max-len */
2
+ import { HydratedDocument, QueryWithHelpers, Schema } from 'mongoose';
3
+ import { ExtractDocType } from '../types';
4
+
5
+ /**
6
+ * Interface for query helpers that support converting results to a `Map`.
7
+ *
8
+ * @template T The type of the `HydratedDocument`.
9
+ */
10
+ export interface ToMapQueryHelpers<RawDocType, HydratedDocType> {
11
+ /**
12
+ * Query helper interface for converting query results into a `Map` keyed by string.
13
+ *
14
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
15
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
16
+ *
17
+ * @remarks
18
+ * - The `toMap` method transforms an array of documents returned by a query into a `Map<string, T>`,
19
+ * where the key is typically derived from a document property (e.g., `_id` as a string).
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * const docsMap = await Model.find().toMap();
24
+ * // docsMap is a Map<string, HydratedDocType>
25
+ * ```
26
+ */
27
+ toMap(
28
+ this: QueryWithHelpers<HydratedDocType[], HydratedDocType>
29
+ ): QueryWithHelpers<Map<string, HydratedDocType>, HydratedDocType>;
30
+ /**
31
+ * Query helper interface for converting query results into a `Map` keyed by string.
32
+ *
33
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
34
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
35
+ *
36
+ * @remarks
37
+ * - The `toMap` method transforms an array of documents returned by a query into a `Map<string, T>`,
38
+ * where the key is typically derived from a document property (e.g., `_id` as a string).
39
+ *
40
+ * @example
41
+ * ```typescript
42
+ * const docsMap = await Model.find().toMap();
43
+ * // docsMap is a Map<string, RawDocType>
44
+ * ```
45
+ */
46
+ toMap(
47
+ this: QueryWithHelpers<RawDocType[], HydratedDocType>
48
+ ): QueryWithHelpers<Map<string, RawDocType>, HydratedDocType>;
49
+ }
50
+
51
+ /**
52
+ * Mongoose plugin to add the `toMap` method to queries.
53
+ *
54
+ * @template T The type of the `HydratedDocument`.
55
+ * @param schema The Mongoose schema to extend.
56
+ */
57
+ const toMapPlugin = <T extends HydratedDocument<any>>(
58
+ schema: Schema<any, any, any, ToMapQueryHelpers<ExtractDocType<T>, T>, any, any, any>,
59
+ ) => {
60
+ // eslint-disable-next-line no-param-reassign
61
+ schema.query.toMap = function (this) {
62
+ const result = this.transform((docs: any) => {
63
+ if (!docs) {
64
+ return new Map();
65
+ }
66
+ if (Array.isArray(docs)) {
67
+ return new Map(docs.map((doc: any) => [doc._id.toString(), doc]));
68
+ }
69
+ return new Map([[docs._id.toString(), docs]]);
70
+ });
71
+ return result;
72
+ };
73
+ };
74
+
75
+ export default toMapPlugin;
@@ -0,0 +1,74 @@
1
+ import { HydratedDocument, QueryWithHelpers, Schema } from 'mongoose';
2
+ import { ExtractDocType } from '../types';
3
+
4
+ /**
5
+ * Interface for query helpers that support converting results to a record (object).
6
+ *
7
+ * @template T The type of the `HydratedDocument`.
8
+ */
9
+ export interface ToRecordsQueryHelpers<RawDocType, HydratedDocType> {
10
+ /**
11
+ * Query helpers for transforming query results into a record (object) keyed by document IDs.
12
+ *
13
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
14
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
15
+ *
16
+ * Provides overloaded `toRecords` methods for use with Mongoose queries, allowing the result
17
+ * array to be converted into a record where each key is the document's `_id` (as a string)
18
+ * and the value is the corresponding document.
19
+ *
20
+ * @example
21
+ * // Usage in a Mongoose query:
22
+ * const records = await Model.find().toRecords();
23
+ * // records is of type Record<string, HydratedDocType>
24
+ */
25
+ toRecords(
26
+ this: QueryWithHelpers<HydratedDocType[], HydratedDocType>
27
+ ): QueryWithHelpers<Record<string, HydratedDocType>, HydratedDocType>;
28
+ /**
29
+ * Query helpers for transforming query results into a record (object) keyed by document IDs.
30
+ *
31
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
32
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
33
+ *
34
+ * Provides overloaded `toRecords` methods for use with Mongoose queries, allowing the result
35
+ * array to be converted into a record where each key is the document's `_id` (as a string)
36
+ * and the value is the corresponding document.
37
+ *
38
+ * @example
39
+ * // Usage in a Mongoose query:
40
+ * const records = await Model.find().toRecords();
41
+ * // records is of type Record<string, RawDocType>
42
+ */
43
+ toRecords(
44
+ this: QueryWithHelpers<RawDocType[], HydratedDocType>
45
+ ): QueryWithHelpers<Record<string, RawDocType>, HydratedDocType>;
46
+ }
47
+
48
+ /**
49
+ * Mongoose plugin to add the `toRecords` method to queries.
50
+ *
51
+ * @template T The type of the `HydratedDocument`.
52
+ * @param schema The Mongoose schema to extend.
53
+ */
54
+ const toRecordsPlugin = <T extends HydratedDocument<any>>(
55
+ schema: Schema<any, any, any, ToRecordsQueryHelpers<ExtractDocType<T>, T>, any, any, any>,
56
+ ) => {
57
+ // eslint-disable-next-line no-param-reassign
58
+ schema.query.toRecords = function toRecords(this) {
59
+ const result = this.transform((docs: any) => {
60
+ if (!docs) {
61
+ return {};
62
+ }
63
+ if (Array.isArray(docs)) {
64
+ return Object.fromEntries(docs.map((doc: any) => [doc._id.toString(), doc]));
65
+ }
66
+ return {
67
+ [docs._id.toString()]: docs,
68
+ };
69
+ });
70
+ return result;
71
+ };
72
+ };
73
+
74
+ export default toRecordsPlugin;
package/src/types.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { HydratedDocument } from 'mongoose';
2
+
3
+ /**
4
+ * Extracts the underlying document type from a Mongoose `HydratedDocument`.
5
+ * This utility type is useful for working with Mongoose models and their hydrated versions.
6
+ *
7
+ * @template T The type of the `HydratedDocument`.
8
+ * @returns The type of the document if `T` is a `HydratedDocument`, otherwise `never`.
9
+ */
10
+ export type ExtractDocType<T> = T extends HydratedDocument<infer U> ? U : never;
@@ -56,4 +56,6 @@ const commentSchema = new Schema<IComment, CommentModelType>({
56
56
 
57
57
  commentSchema.index({ user: 1 });
58
58
 
59
- export default model<IComment, CommentModelType>('Comment', commentSchema);
59
+ const Comment = model<IComment, CommentModelType>('Comment', commentSchema);
60
+
61
+ export default Comment;
@@ -8,6 +8,12 @@ import {
8
8
  model,
9
9
  } from 'mongoose';
10
10
  import addressSchema, { AddressInstance, IAddress } from './embedded/address';
11
+ import {
12
+ toMap,
13
+ ToMapQueryHelpers,
14
+ toRecords,
15
+ ToRecordsQueryHelpers,
16
+ } from '../../../src';
11
17
 
12
18
  export interface IUser {
13
19
  _id: Types.ObjectId;
@@ -33,7 +39,8 @@ export type UserHydratedDocument = HydratedDocument<IUser, IUserDocumentOverride
33
39
 
34
40
  export type UserModelType = Model<
35
41
  IUser,
36
- {},
42
+ ToMapQueryHelpers<IUser, UserHydratedDocument> &
43
+ ToRecordsQueryHelpers<IUser, UserHydratedDocument>,
37
44
  IUserDocumentOverrides,
38
45
  IUserVirtuals,
39
46
  UserHydratedDocument
@@ -73,4 +80,9 @@ userSchema.virtual('fullName')
73
80
  return `${this.name} ${this.surname}`;
74
81
  });
75
82
 
76
- export default model<IUser, UserModelType>('User', userSchema);
83
+ userSchema.plugin(toMap);
84
+ userSchema.plugin(toRecords);
85
+
86
+ const User = model<IUser, UserModelType>('User', userSchema);
87
+
88
+ export default User;
@@ -0,0 +1,75 @@
1
+ import User, { UserHydratedDocument } from './initializers/models/user';
2
+
3
+ let user: UserHydratedDocument;
4
+
5
+ beforeAll(async () => {
6
+ user = await User.create({
7
+ name: 'Nicolò',
8
+ surname: 'Zandarin',
9
+ email: 'nicolo.zandarin@email.com',
10
+ password: 'password',
11
+ address: {
12
+ streetAddress: '',
13
+ postalCode: '',
14
+ city: '',
15
+ province: '',
16
+ country: 'Italy',
17
+ },
18
+ });
19
+ });
20
+
21
+ describe('toMap', () => {
22
+ it('should return a map with the found documents', async () => {
23
+ const users = await User
24
+ .find()
25
+ .toMap();
26
+ expect(users).toBeTruthy();
27
+ expect(users.has(user._id.toString())).toBe(true);
28
+ expect(users.get(user._id.toString())!).toBeInstanceOf(User);
29
+ });
30
+
31
+ it('should return a map with lean documents', async () => {
32
+ const users = await User
33
+ .find()
34
+ .lean()
35
+ .toMap();
36
+ expect(users).toBeTruthy();
37
+ expect(users.has(user._id.toString())).toBe(true);
38
+ expect(users.get(user._id.toString())!).not.toBeInstanceOf(User);
39
+ });
40
+
41
+ it('should return an empty map if no documents are found', async () => {
42
+ const users = await User
43
+ .find({ email: 'non-existent@email.com' })
44
+ .toMap();
45
+ expect(users).toBeTruthy();
46
+ expect(users.size).toBe(0);
47
+ });
48
+ });
49
+
50
+ describe('toRecords', () => {
51
+ it('should return a map with the found documents', async () => {
52
+ const users = await User
53
+ .find()
54
+ .toRecords();
55
+ expect(users).toBeTruthy();
56
+ expect(users[user.id]).toBeInstanceOf(User);
57
+ });
58
+
59
+ it('should return a map with lean documents', async () => {
60
+ const users = await User
61
+ .find()
62
+ .lean()
63
+ .toRecords();
64
+ expect(users).toBeTruthy();
65
+ expect(users[user._id.toString()]).not.toBeInstanceOf(User);
66
+ });
67
+
68
+ it('should return an empty map if no documents are found', async () => {
69
+ const users = await User
70
+ .find({ email: 'non-existent@email.com' })
71
+ .toRecords();
72
+ expect(users).toBeTruthy();
73
+ expect(Object.keys(users)).toHaveLength(0);
74
+ });
75
+ });
package/tsup.config.ts CHANGED
@@ -1,9 +1,10 @@
1
- import { defineConfig } from "tsup";
1
+ // eslint-disable-next-line import/no-extraneous-dependencies
2
+ import { defineConfig } from 'tsup';
2
3
 
3
4
  export default defineConfig({
4
- entryPoints: ["src/index.ts"],
5
- format: ["cjs", "esm"],
5
+ entryPoints: ['src/index.ts'],
6
+ format: ['cjs', 'esm'],
6
7
  dts: true,
7
- outDir: "dist",
8
+ outDir: 'dist',
8
9
  clean: true,
9
10
  });