mongoose-utility-kit 0.1.0 → 0.3.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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # mongoose-utility-kit
2
2
 
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 794bd55: added overload type of toMap & toRecords to handle virtuals
8
+
9
+ ## 0.2.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 9217086: fixed ToMapQueryHelpers & ToRecordsQueryHelpers interfaces
14
+
3
15
  ## 0.1.0
4
16
 
5
17
  ### Minor Changes
package/README.md CHANGED
@@ -138,7 +138,7 @@ These plugins provide helper methods for Mongoose queries to transform the resul
138
138
 
139
139
  type MyModelType = Model<
140
140
  IMyModel,
141
- ToMapQueryHelpers<MyModelHydratedDocument> & ToRecordsQueryHelpers<MyModelHydratedDocument>,
141
+ ToMapQueryHelpers<IMyModel, MyModelHydratedDocument> & ToRecordsQueryHelpers<IMyModel, MyModelHydratedDocument>,
142
142
  {},
143
143
  {},
144
144
  MyModelHydratedDocument
package/dist/index.cjs CHANGED
@@ -29,42 +29,38 @@ __export(index_exports, {
29
29
  module.exports = __toCommonJS(index_exports);
30
30
 
31
31
  // src/plugins/toMap.ts
32
- function toMap() {
33
- const result = this.transform((docs) => {
34
- if (!docs) {
35
- return /* @__PURE__ */ new Map();
36
- }
37
- if (Array.isArray(docs)) {
38
- return new Map(docs.map((doc) => [doc._id.toString(), doc]));
39
- }
40
- return /* @__PURE__ */ new Map([[docs._id.toString(), docs]]);
41
- });
42
- return result;
43
- }
44
32
  var toMapPlugin = (schema) => {
45
- schema.query.toMap = toMap;
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
+ };
46
45
  };
47
46
  var toMap_default = toMapPlugin;
48
47
 
49
48
  // src/plugins/toRecords.ts
50
- function toRecords() {
51
- const result = this.transform((docs) => {
52
- if (!docs) {
53
- return {};
54
- }
55
- if (Array.isArray(docs)) {
56
- return Object.fromEntries(
57
- docs.map((doc) => [doc._id.toString(), doc])
58
- );
59
- }
60
- return {
61
- [docs._id.toString()]: docs
62
- };
63
- });
64
- return result;
65
- }
66
49
  var toRecordsPlugin = (schema) => {
67
- schema.query.toRecords = toRecords;
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
+ };
68
64
  };
69
65
  var toRecords_default = toRecordsPlugin;
70
66
 
package/dist/index.d.cts CHANGED
@@ -7,20 +7,83 @@ import { HydratedDocument, Schema, QueryWithHelpers, Document, PopulatedDoc, Typ
7
7
  * @template T The type of the `HydratedDocument`.
8
8
  * @returns The type of the document if `T` is a `HydratedDocument`, otherwise `never`.
9
9
  */
10
- type ExtractDocType<T> = T extends HydratedDocument<infer U> ? U : never;
10
+ type ExtractRawDocType<T> = T extends HydratedDocument<infer U> ? U : never;
11
+ /**
12
+ * Extracts the virtuals type from a Mongoose `HydratedDocument`.
13
+ * This utility type is useful for accessing the shape of virtual properties
14
+ * defined on Mongoose schemas.
15
+ *
16
+ * @template T The type of the `HydratedDocument`.
17
+ * @returns The type of the virtuals if `T` is a `HydratedDocument`, otherwise `never`.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * type Virtuals = ExtractVirtualsType<HydratedDocument<MyDoc, MyVirtuals>>;
22
+ * // Virtuals is inferred as MyVirtuals
23
+ * ```
24
+ */
25
+ type ExtractVirtualsType<T> = T extends HydratedDocument<any, infer U> ? U : never;
11
26
 
12
27
  /**
13
28
  * Interface for query helpers that support converting results to a `Map`.
14
29
  *
15
30
  * @template T The type of the `HydratedDocument`.
16
31
  */
17
- interface ToMapQueryHelpers<T extends HydratedDocument<any>> {
32
+ interface ToMapQueryHelpers<RawDocType, HydratedDocType, TVirtuals> {
18
33
  /**
19
- * Converts the query results into a `Map` where the key is the document's _id.
34
+ * Query helper interface for converting query results into a `Map` keyed by string,
35
+ * including virtual properties.
36
+ *
37
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
38
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
39
+ * @template TVirtuals - The type representing virtual properties added to the raw document.
20
40
  *
21
- * @returns A QueryWithHelpers instance that returns a `Map` of documents.
41
+ * @remarks
42
+ * - This overload of `toMap` is used when the query returns documents that include virtuals.
43
+ * - The result is a `Map<string, RawDocType & TVirtuals>`, where the key is typically derived
44
+ * from a document property such as `_id`.
45
+ *
46
+ * @example
47
+ * ```typescript
48
+ * const docsMap = await Model.find().toMap();
49
+ * // docsMap is a Map<string, RawDocType & TVirtuals>
50
+ * ```
22
51
  */
23
- toMap(): QueryWithHelpers<Map<string, T>, T, ToMapQueryHelpers<T>, ExtractDocType<T>>;
52
+ toMap(this: QueryWithHelpers<(RawDocType & TVirtuals)[], HydratedDocType>): QueryWithHelpers<Map<string, RawDocType & TVirtuals>, HydratedDocType>;
53
+ /**
54
+ * Query helper interface for converting query results into a `Map` keyed by string.
55
+ *
56
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
57
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
58
+ *
59
+ * @remarks
60
+ * - The `toMap` method transforms an array of documents returned by a query into a `Map<string, T>`,
61
+ * where the key is typically derived from a document property (e.g., `_id` as a string).
62
+ *
63
+ * @example
64
+ * ```typescript
65
+ * const docsMap = await Model.find().toMap();
66
+ * // docsMap is a Map<string, HydratedDocType>
67
+ * ```
68
+ */
69
+ toMap(this: QueryWithHelpers<HydratedDocType[], HydratedDocType>): QueryWithHelpers<Map<string, HydratedDocType>, HydratedDocType>;
70
+ /**
71
+ * Query helper interface for converting query results into a `Map` keyed by string.
72
+ *
73
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
74
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
75
+ *
76
+ * @remarks
77
+ * - The `toMap` method transforms an array of documents returned by a query into a `Map<string, T>`,
78
+ * where the key is typically derived from a document property (e.g., `_id` as a string).
79
+ *
80
+ * @example
81
+ * ```typescript
82
+ * const docsMap = await Model.find().toMap();
83
+ * // docsMap is a Map<string, RawDocType>
84
+ * ```
85
+ */
86
+ toMap(this: QueryWithHelpers<RawDocType[], HydratedDocType>): QueryWithHelpers<Map<string, RawDocType>, HydratedDocType>;
24
87
  }
25
88
  /**
26
89
  * Mongoose plugin to add the `toMap` method to queries.
@@ -28,20 +91,67 @@ interface ToMapQueryHelpers<T extends HydratedDocument<any>> {
28
91
  * @template T The type of the `HydratedDocument`.
29
92
  * @param schema The Mongoose schema to extend.
30
93
  */
31
- declare const toMapPlugin: <T extends unknown>(schema: Schema<any, any, any, ToMapQueryHelpers<T>, any, any, any>) => void;
94
+ declare const toMapPlugin: <T extends unknown>(schema: Schema<any, any, any, ToMapQueryHelpers<ExtractRawDocType<T>, T, ExtractVirtualsType<T>>, any, any, any>) => void;
32
95
 
33
96
  /**
34
97
  * Interface for query helpers that support converting results to a record (object).
35
98
  *
36
99
  * @template T The type of the `HydratedDocument`.
37
100
  */
38
- interface ToRecordsQueryHelpers<T extends HydratedDocument<any>> {
101
+ interface ToRecordsQueryHelpers<RawDocType, HydratedDocType, TVirtuals> {
102
+ /**
103
+ * Query helper for transforming query results into a `Record<string, T>` object,
104
+ * including virtual properties.
105
+ *
106
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
107
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
108
+ * @template TVirtuals - The type representing virtual properties added to the raw document.
109
+ *
110
+ * @remarks
111
+ * - This overload is used when the query returns documents that include virtuals.
112
+ * - The result is a plain object (`Record<string, RawDocType & TVirtuals>`) where each key
113
+ * corresponds to the document's `_id` (as a string), and the value includes both
114
+ * raw fields and virtuals.
115
+ *
116
+ * @example
117
+ * ```ts
118
+ * const records = await Model.find().toRecords();
119
+ * // records is of type Record<string, RawDocType & TVirtuals>
120
+ * ```
121
+ */
122
+ toRecords(this: QueryWithHelpers<(RawDocType & TVirtuals)[], HydratedDocType>): QueryWithHelpers<Record<string, RawDocType & TVirtuals>, HydratedDocType>;
39
123
  /**
40
- * Converts the query results into a record (object) where the key is the document's _id.
124
+ * Query helpers for transforming query results into a record (object) keyed by document IDs.
125
+ *
126
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
127
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
128
+ *
129
+ * Provides overloaded `toRecords` methods for use with Mongoose queries, allowing the result
130
+ * array to be converted into a record where each key is the document's `_id` (as a string)
131
+ * and the value is the corresponding document.
132
+ *
133
+ * @example
134
+ * // Usage in a Mongoose query:
135
+ * const records = await Model.find().toRecords();
136
+ * // records is of type Record<string, HydratedDocType>
137
+ */
138
+ toRecords(this: QueryWithHelpers<HydratedDocType[], HydratedDocType>): QueryWithHelpers<Record<string, HydratedDocType>, HydratedDocType>;
139
+ /**
140
+ * Query helpers for transforming query results into a record (object) keyed by document IDs.
141
+ *
142
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
143
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
144
+ *
145
+ * Provides overloaded `toRecords` methods for use with Mongoose queries, allowing the result
146
+ * array to be converted into a record where each key is the document's `_id` (as a string)
147
+ * and the value is the corresponding document.
41
148
  *
42
- * @returns A QueryWithHelpers instance that returns a Record of documents.
149
+ * @example
150
+ * // Usage in a Mongoose query:
151
+ * const records = await Model.find().toRecords();
152
+ * // records is of type Record<string, RawDocType>
43
153
  */
44
- toRecords(): QueryWithHelpers<Record<string, T>, T, ToRecordsQueryHelpers<T>, ExtractDocType<T>>;
154
+ toRecords(this: QueryWithHelpers<RawDocType[], HydratedDocType>): QueryWithHelpers<Record<string, RawDocType>, HydratedDocType>;
45
155
  }
46
156
  /**
47
157
  * Mongoose plugin to add the `toRecords` method to queries.
@@ -49,7 +159,7 @@ interface ToRecordsQueryHelpers<T extends HydratedDocument<any>> {
49
159
  * @template T The type of the `HydratedDocument`.
50
160
  * @param schema The Mongoose schema to extend.
51
161
  */
52
- declare const toRecordsPlugin: <T extends unknown>(schema: Schema<any, any, any, ToRecordsQueryHelpers<T>, any, any, any>) => void;
162
+ declare const toRecordsPlugin: <T extends unknown>(schema: Schema<any, any, any, ToRecordsQueryHelpers<ExtractRawDocType<T>, T, ExtractVirtualsType<T>>, any, any, any>) => void;
53
163
 
54
164
  /**
55
165
  * Extracts the ID from a populated Mongoose document.
package/dist/index.d.ts CHANGED
@@ -7,20 +7,83 @@ import { HydratedDocument, Schema, QueryWithHelpers, Document, PopulatedDoc, Typ
7
7
  * @template T The type of the `HydratedDocument`.
8
8
  * @returns The type of the document if `T` is a `HydratedDocument`, otherwise `never`.
9
9
  */
10
- type ExtractDocType<T> = T extends HydratedDocument<infer U> ? U : never;
10
+ type ExtractRawDocType<T> = T extends HydratedDocument<infer U> ? U : never;
11
+ /**
12
+ * Extracts the virtuals type from a Mongoose `HydratedDocument`.
13
+ * This utility type is useful for accessing the shape of virtual properties
14
+ * defined on Mongoose schemas.
15
+ *
16
+ * @template T The type of the `HydratedDocument`.
17
+ * @returns The type of the virtuals if `T` is a `HydratedDocument`, otherwise `never`.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * type Virtuals = ExtractVirtualsType<HydratedDocument<MyDoc, MyVirtuals>>;
22
+ * // Virtuals is inferred as MyVirtuals
23
+ * ```
24
+ */
25
+ type ExtractVirtualsType<T> = T extends HydratedDocument<any, infer U> ? U : never;
11
26
 
12
27
  /**
13
28
  * Interface for query helpers that support converting results to a `Map`.
14
29
  *
15
30
  * @template T The type of the `HydratedDocument`.
16
31
  */
17
- interface ToMapQueryHelpers<T extends HydratedDocument<any>> {
32
+ interface ToMapQueryHelpers<RawDocType, HydratedDocType, TVirtuals> {
18
33
  /**
19
- * Converts the query results into a `Map` where the key is the document's _id.
34
+ * Query helper interface for converting query results into a `Map` keyed by string,
35
+ * including virtual properties.
36
+ *
37
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
38
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
39
+ * @template TVirtuals - The type representing virtual properties added to the raw document.
20
40
  *
21
- * @returns A QueryWithHelpers instance that returns a `Map` of documents.
41
+ * @remarks
42
+ * - This overload of `toMap` is used when the query returns documents that include virtuals.
43
+ * - The result is a `Map<string, RawDocType & TVirtuals>`, where the key is typically derived
44
+ * from a document property such as `_id`.
45
+ *
46
+ * @example
47
+ * ```typescript
48
+ * const docsMap = await Model.find().toMap();
49
+ * // docsMap is a Map<string, RawDocType & TVirtuals>
50
+ * ```
22
51
  */
23
- toMap(): QueryWithHelpers<Map<string, T>, T, ToMapQueryHelpers<T>, ExtractDocType<T>>;
52
+ toMap(this: QueryWithHelpers<(RawDocType & TVirtuals)[], HydratedDocType>): QueryWithHelpers<Map<string, RawDocType & TVirtuals>, HydratedDocType>;
53
+ /**
54
+ * Query helper interface for converting query results into a `Map` keyed by string.
55
+ *
56
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
57
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
58
+ *
59
+ * @remarks
60
+ * - The `toMap` method transforms an array of documents returned by a query into a `Map<string, T>`,
61
+ * where the key is typically derived from a document property (e.g., `_id` as a string).
62
+ *
63
+ * @example
64
+ * ```typescript
65
+ * const docsMap = await Model.find().toMap();
66
+ * // docsMap is a Map<string, HydratedDocType>
67
+ * ```
68
+ */
69
+ toMap(this: QueryWithHelpers<HydratedDocType[], HydratedDocType>): QueryWithHelpers<Map<string, HydratedDocType>, HydratedDocType>;
70
+ /**
71
+ * Query helper interface for converting query results into a `Map` keyed by string.
72
+ *
73
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
74
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
75
+ *
76
+ * @remarks
77
+ * - The `toMap` method transforms an array of documents returned by a query into a `Map<string, T>`,
78
+ * where the key is typically derived from a document property (e.g., `_id` as a string).
79
+ *
80
+ * @example
81
+ * ```typescript
82
+ * const docsMap = await Model.find().toMap();
83
+ * // docsMap is a Map<string, RawDocType>
84
+ * ```
85
+ */
86
+ toMap(this: QueryWithHelpers<RawDocType[], HydratedDocType>): QueryWithHelpers<Map<string, RawDocType>, HydratedDocType>;
24
87
  }
25
88
  /**
26
89
  * Mongoose plugin to add the `toMap` method to queries.
@@ -28,20 +91,67 @@ interface ToMapQueryHelpers<T extends HydratedDocument<any>> {
28
91
  * @template T The type of the `HydratedDocument`.
29
92
  * @param schema The Mongoose schema to extend.
30
93
  */
31
- declare const toMapPlugin: <T extends unknown>(schema: Schema<any, any, any, ToMapQueryHelpers<T>, any, any, any>) => void;
94
+ declare const toMapPlugin: <T extends unknown>(schema: Schema<any, any, any, ToMapQueryHelpers<ExtractRawDocType<T>, T, ExtractVirtualsType<T>>, any, any, any>) => void;
32
95
 
33
96
  /**
34
97
  * Interface for query helpers that support converting results to a record (object).
35
98
  *
36
99
  * @template T The type of the `HydratedDocument`.
37
100
  */
38
- interface ToRecordsQueryHelpers<T extends HydratedDocument<any>> {
101
+ interface ToRecordsQueryHelpers<RawDocType, HydratedDocType, TVirtuals> {
102
+ /**
103
+ * Query helper for transforming query results into a `Record<string, T>` object,
104
+ * including virtual properties.
105
+ *
106
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
107
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
108
+ * @template TVirtuals - The type representing virtual properties added to the raw document.
109
+ *
110
+ * @remarks
111
+ * - This overload is used when the query returns documents that include virtuals.
112
+ * - The result is a plain object (`Record<string, RawDocType & TVirtuals>`) where each key
113
+ * corresponds to the document's `_id` (as a string), and the value includes both
114
+ * raw fields and virtuals.
115
+ *
116
+ * @example
117
+ * ```ts
118
+ * const records = await Model.find().toRecords();
119
+ * // records is of type Record<string, RawDocType & TVirtuals>
120
+ * ```
121
+ */
122
+ toRecords(this: QueryWithHelpers<(RawDocType & TVirtuals)[], HydratedDocType>): QueryWithHelpers<Record<string, RawDocType & TVirtuals>, HydratedDocType>;
39
123
  /**
40
- * Converts the query results into a record (object) where the key is the document's _id.
124
+ * Query helpers for transforming query results into a record (object) keyed by document IDs.
125
+ *
126
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
127
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
128
+ *
129
+ * Provides overloaded `toRecords` methods for use with Mongoose queries, allowing the result
130
+ * array to be converted into a record where each key is the document's `_id` (as a string)
131
+ * and the value is the corresponding document.
132
+ *
133
+ * @example
134
+ * // Usage in a Mongoose query:
135
+ * const records = await Model.find().toRecords();
136
+ * // records is of type Record<string, HydratedDocType>
137
+ */
138
+ toRecords(this: QueryWithHelpers<HydratedDocType[], HydratedDocType>): QueryWithHelpers<Record<string, HydratedDocType>, HydratedDocType>;
139
+ /**
140
+ * Query helpers for transforming query results into a record (object) keyed by document IDs.
141
+ *
142
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
143
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
144
+ *
145
+ * Provides overloaded `toRecords` methods for use with Mongoose queries, allowing the result
146
+ * array to be converted into a record where each key is the document's `_id` (as a string)
147
+ * and the value is the corresponding document.
41
148
  *
42
- * @returns A QueryWithHelpers instance that returns a Record of documents.
149
+ * @example
150
+ * // Usage in a Mongoose query:
151
+ * const records = await Model.find().toRecords();
152
+ * // records is of type Record<string, RawDocType>
43
153
  */
44
- toRecords(): QueryWithHelpers<Record<string, T>, T, ToRecordsQueryHelpers<T>, ExtractDocType<T>>;
154
+ toRecords(this: QueryWithHelpers<RawDocType[], HydratedDocType>): QueryWithHelpers<Record<string, RawDocType>, HydratedDocType>;
45
155
  }
46
156
  /**
47
157
  * Mongoose plugin to add the `toRecords` method to queries.
@@ -49,7 +159,7 @@ interface ToRecordsQueryHelpers<T extends HydratedDocument<any>> {
49
159
  * @template T The type of the `HydratedDocument`.
50
160
  * @param schema The Mongoose schema to extend.
51
161
  */
52
- declare const toRecordsPlugin: <T extends unknown>(schema: Schema<any, any, any, ToRecordsQueryHelpers<T>, any, any, any>) => void;
162
+ declare const toRecordsPlugin: <T extends unknown>(schema: Schema<any, any, any, ToRecordsQueryHelpers<ExtractRawDocType<T>, T, ExtractVirtualsType<T>>, any, any, any>) => void;
53
163
 
54
164
  /**
55
165
  * Extracts the ID from a populated Mongoose document.
package/dist/index.js CHANGED
@@ -1,40 +1,36 @@
1
1
  // src/plugins/toMap.ts
2
- function toMap() {
3
- const result = this.transform((docs) => {
4
- if (!docs) {
5
- return /* @__PURE__ */ new Map();
6
- }
7
- if (Array.isArray(docs)) {
8
- return new Map(docs.map((doc) => [doc._id.toString(), doc]));
9
- }
10
- return /* @__PURE__ */ new Map([[docs._id.toString(), docs]]);
11
- });
12
- return result;
13
- }
14
2
  var toMapPlugin = (schema) => {
15
- schema.query.toMap = toMap;
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
+ };
16
15
  };
17
16
  var toMap_default = toMapPlugin;
18
17
 
19
18
  // src/plugins/toRecords.ts
20
- function toRecords() {
21
- const result = this.transform((docs) => {
22
- if (!docs) {
23
- return {};
24
- }
25
- if (Array.isArray(docs)) {
26
- return Object.fromEntries(
27
- docs.map((doc) => [doc._id.toString(), doc])
28
- );
29
- }
30
- return {
31
- [docs._id.toString()]: docs
32
- };
33
- });
34
- return result;
35
- }
36
19
  var toRecordsPlugin = (schema) => {
37
- schema.query.toRecords = toRecords;
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
+ };
38
34
  };
39
35
  var toRecords_default = toRecordsPlugin;
40
36
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mongoose-utility-kit",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "A set of utility functions for the Mongoose library",
5
5
  "keywords": [
6
6
  "mongoose",
@@ -42,6 +42,7 @@
42
42
  "jest": "^29.7.0",
43
43
  "mongodb-memory-server": "^10.1.4",
44
44
  "mongoose": ">=8",
45
+ "mongoose-lean-virtuals": "^2.0.0",
45
46
  "ts-jest": "^29.2.5",
46
47
  "tsup": "^8.3.6",
47
48
  "typescript": "^5.7.3"
@@ -1,50 +1,73 @@
1
+ /* eslint-disable max-len */
1
2
  import { HydratedDocument, QueryWithHelpers, Schema } from 'mongoose';
2
- import { ExtractDocType } from '../types';
3
+ import { ExtractRawDocType, ExtractVirtualsType } from '../types';
3
4
 
4
5
  /**
5
6
  * Interface for query helpers that support converting results to a `Map`.
6
7
  *
7
8
  * @template T The type of the `HydratedDocument`.
8
9
  */
9
- export interface ToMapQueryHelpers<T extends HydratedDocument<any>> {
10
+ export interface ToMapQueryHelpers<RawDocType, HydratedDocType, TVirtuals> {
10
11
  /**
11
- * Converts the query results into a `Map` where the key is the document's _id.
12
+ * Query helper interface for converting query results into a `Map` keyed by string,
13
+ * including virtual properties.
12
14
  *
13
- * @returns A QueryWithHelpers instance that returns a `Map` of documents.
15
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
16
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
17
+ * @template TVirtuals - The type representing virtual properties added to the raw document.
18
+ *
19
+ * @remarks
20
+ * - This overload of `toMap` is used when the query returns documents that include virtuals.
21
+ * - The result is a `Map<string, RawDocType & TVirtuals>`, where the key is typically derived
22
+ * from a document property such as `_id`.
23
+ *
24
+ * @example
25
+ * ```typescript
26
+ * const docsMap = await Model.find().toMap();
27
+ * // docsMap is a Map<string, RawDocType & TVirtuals>
28
+ * ```
14
29
  */
15
- toMap(): QueryWithHelpers<
16
- Map<string, T>,
17
- T,
18
- ToMapQueryHelpers<T>,
19
- ExtractDocType<T>
20
- >,
21
- }
22
-
23
- /**
24
- * Function to transform query results into a `Map`.
25
- *
26
- * @template T The type of the `HydratedDocument`.
27
- * @this QueryWithHelpers instance.
28
- * @returns The transformed query result as a `Map`.
29
- */
30
- function toMap<T extends HydratedDocument<any>>(
31
- this: QueryWithHelpers<
32
- Map<string, T>,
33
- T,
34
- ToMapQueryHelpers<T>,
35
- ExtractDocType<T>
36
- >,
37
- ) {
38
- const result = this.transform((docs: any) => {
39
- if (!docs) {
40
- return new Map();
41
- }
42
- if (Array.isArray(docs)) {
43
- return new Map(docs.map((doc: any) => [doc._id.toString(), doc]));
44
- }
45
- return new Map([[docs._id.toString(), docs]]);
46
- });
47
- return result;
30
+ toMap(
31
+ this: QueryWithHelpers<(RawDocType & TVirtuals)[], HydratedDocType>
32
+ ): QueryWithHelpers<Map<string, RawDocType & TVirtuals>, HydratedDocType>;
33
+ /**
34
+ * Query helper interface for converting query results into a `Map` keyed by string.
35
+ *
36
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
37
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
38
+ *
39
+ * @remarks
40
+ * - The `toMap` method transforms an array of documents returned by a query into a `Map<string, T>`,
41
+ * where the key is typically derived from a document property (e.g., `_id` as a string).
42
+ *
43
+ * @example
44
+ * ```typescript
45
+ * const docsMap = await Model.find().toMap();
46
+ * // docsMap is a Map<string, HydratedDocType>
47
+ * ```
48
+ */
49
+ toMap(
50
+ this: QueryWithHelpers<HydratedDocType[], HydratedDocType>
51
+ ): QueryWithHelpers<Map<string, HydratedDocType>, HydratedDocType>;
52
+ /**
53
+ * Query helper interface for converting query results into a `Map` keyed by string.
54
+ *
55
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
56
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
57
+ *
58
+ * @remarks
59
+ * - The `toMap` method transforms an array of documents returned by a query into a `Map<string, T>`,
60
+ * where the key is typically derived from a document property (e.g., `_id` as a string).
61
+ *
62
+ * @example
63
+ * ```typescript
64
+ * const docsMap = await Model.find().toMap();
65
+ * // docsMap is a Map<string, RawDocType>
66
+ * ```
67
+ */
68
+ toMap(
69
+ this: QueryWithHelpers<RawDocType[], HydratedDocType>
70
+ ): QueryWithHelpers<Map<string, RawDocType>, HydratedDocType>;
48
71
  }
49
72
 
50
73
  /**
@@ -54,10 +77,21 @@ function toMap<T extends HydratedDocument<any>>(
54
77
  * @param schema The Mongoose schema to extend.
55
78
  */
56
79
  const toMapPlugin = <T extends HydratedDocument<any>>(
57
- schema: Schema<any, any, any, ToMapQueryHelpers<T>, any, any, any>,
80
+ schema: Schema<any, any, any, ToMapQueryHelpers<ExtractRawDocType<T>, T, ExtractVirtualsType<T>>, any, any, any>,
58
81
  ) => {
59
82
  // eslint-disable-next-line no-param-reassign
60
- schema.query.toMap = toMap;
83
+ schema.query.toMap = function (this) {
84
+ const result = this.transform((docs: any) => {
85
+ if (!docs) {
86
+ return new Map();
87
+ }
88
+ if (Array.isArray(docs)) {
89
+ return new Map(docs.map((doc: any) => [doc._id.toString(), doc]));
90
+ }
91
+ return new Map([[docs._id.toString(), docs]]);
92
+ });
93
+ return result;
94
+ };
61
95
  };
62
96
 
63
97
  export default toMapPlugin;
@@ -1,54 +1,71 @@
1
1
  import { HydratedDocument, QueryWithHelpers, Schema } from 'mongoose';
2
- import { ExtractDocType } from '../types';
2
+ import { ExtractRawDocType, ExtractVirtualsType } from '../types';
3
3
 
4
4
  /**
5
5
  * Interface for query helpers that support converting results to a record (object).
6
6
  *
7
7
  * @template T The type of the `HydratedDocument`.
8
8
  */
9
- export interface ToRecordsQueryHelpers<T extends HydratedDocument<any>> {
9
+ export interface ToRecordsQueryHelpers<RawDocType, HydratedDocType, TVirtuals> {
10
10
  /**
11
- * Converts the query results into a record (object) where the key is the document's _id.
11
+ * Query helper for transforming query results into a `Record<string, T>` object,
12
+ * including virtual properties.
12
13
  *
13
- * @returns A QueryWithHelpers instance that returns a Record of documents.
14
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
15
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
16
+ * @template TVirtuals - The type representing virtual properties added to the raw document.
17
+ *
18
+ * @remarks
19
+ * - This overload is used when the query returns documents that include virtuals.
20
+ * - The result is a plain object (`Record<string, RawDocType & TVirtuals>`) where each key
21
+ * corresponds to the document's `_id` (as a string), and the value includes both
22
+ * raw fields and virtuals.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * const records = await Model.find().toRecords();
27
+ * // records is of type Record<string, RawDocType & TVirtuals>
28
+ * ```
14
29
  */
15
- toRecords(): QueryWithHelpers<
16
- Record<string, T>,
17
- T,
18
- ToRecordsQueryHelpers<T>,
19
- ExtractDocType<T>
20
- >,
21
- }
22
-
23
- /**
24
- * Function to transform query results into a record (object).
25
- *
26
- * @template T The type of the `HydratedDocument`.
27
- * @this QueryWithHelpers instance.
28
- * @returns The transformed query result as a Record.
29
- */
30
- function toRecords<T extends HydratedDocument<any>>(
31
- this: QueryWithHelpers<
32
- Record<string, T>,
33
- T,
34
- ToRecordsQueryHelpers<T>,
35
- ExtractDocType<T>
36
- >,
37
- ) {
38
- const result = this.transform((docs: any) => {
39
- if (!docs) {
40
- return {};
41
- }
42
- if (Array.isArray(docs)) {
43
- return Object.fromEntries(
44
- docs.map((doc: any) => [doc._id.toString(), doc]),
45
- ) as Record<string, T>;
46
- }
47
- return {
48
- [docs._id.toString()]: docs,
49
- };
50
- });
51
- return result;
30
+ toRecords(
31
+ this: QueryWithHelpers<(RawDocType & TVirtuals)[], HydratedDocType>
32
+ ): QueryWithHelpers<Record<string, RawDocType & TVirtuals>, HydratedDocType>;
33
+ /**
34
+ * Query helpers for transforming query results into a record (object) keyed by document IDs.
35
+ *
36
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
37
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
38
+ *
39
+ * Provides overloaded `toRecords` methods for use with Mongoose queries, allowing the result
40
+ * array to be converted into a record where each key is the document's `_id` (as a string)
41
+ * and the value is the corresponding document.
42
+ *
43
+ * @example
44
+ * // Usage in a Mongoose query:
45
+ * const records = await Model.find().toRecords();
46
+ * // records is of type Record<string, HydratedDocType>
47
+ */
48
+ toRecords(
49
+ this: QueryWithHelpers<HydratedDocType[], HydratedDocType>
50
+ ): QueryWithHelpers<Record<string, HydratedDocType>, HydratedDocType>;
51
+ /**
52
+ * Query helpers for transforming query results into a record (object) keyed by document IDs.
53
+ *
54
+ * @template RawDocType - The type representing the raw document as returned by MongoDB.
55
+ * @template HydratedDocType - The type representing the hydrated Mongoose document.
56
+ *
57
+ * Provides overloaded `toRecords` methods for use with Mongoose queries, allowing the result
58
+ * array to be converted into a record where each key is the document's `_id` (as a string)
59
+ * and the value is the corresponding document.
60
+ *
61
+ * @example
62
+ * // Usage in a Mongoose query:
63
+ * const records = await Model.find().toRecords();
64
+ * // records is of type Record<string, RawDocType>
65
+ */
66
+ toRecords(
67
+ this: QueryWithHelpers<RawDocType[], HydratedDocType>
68
+ ): QueryWithHelpers<Record<string, RawDocType>, HydratedDocType>;
52
69
  }
53
70
 
54
71
  /**
@@ -58,10 +75,33 @@ function toRecords<T extends HydratedDocument<any>>(
58
75
  * @param schema The Mongoose schema to extend.
59
76
  */
60
77
  const toRecordsPlugin = <T extends HydratedDocument<any>>(
61
- schema: Schema<any, any, any, ToRecordsQueryHelpers<T>, any, any, any>,
78
+ schema: Schema<
79
+ any,
80
+ any,
81
+ any,
82
+ ToRecordsQueryHelpers<ExtractRawDocType<T>,
83
+ T,
84
+ ExtractVirtualsType<T>>,
85
+ any,
86
+ any,
87
+ any
88
+ >,
62
89
  ) => {
63
90
  // eslint-disable-next-line no-param-reassign
64
- schema.query.toRecords = toRecords;
91
+ schema.query.toRecords = function toRecords(this) {
92
+ const result = this.transform((docs: any) => {
93
+ if (!docs) {
94
+ return {};
95
+ }
96
+ if (Array.isArray(docs)) {
97
+ return Object.fromEntries(docs.map((doc: any) => [doc._id.toString(), doc]));
98
+ }
99
+ return {
100
+ [docs._id.toString()]: docs,
101
+ };
102
+ });
103
+ return result;
104
+ };
65
105
  };
66
106
 
67
107
  export default toRecordsPlugin;
package/src/types.ts CHANGED
@@ -7,4 +7,20 @@ import { HydratedDocument } from 'mongoose';
7
7
  * @template T The type of the `HydratedDocument`.
8
8
  * @returns The type of the document if `T` is a `HydratedDocument`, otherwise `never`.
9
9
  */
10
- export type ExtractDocType<T> = T extends HydratedDocument<infer U> ? U : never;
10
+ export type ExtractRawDocType<T> = T extends HydratedDocument<infer U> ? U : never;
11
+
12
+ /**
13
+ * Extracts the virtuals type from a Mongoose `HydratedDocument`.
14
+ * This utility type is useful for accessing the shape of virtual properties
15
+ * defined on Mongoose schemas.
16
+ *
17
+ * @template T The type of the `HydratedDocument`.
18
+ * @returns The type of the virtuals if `T` is a `HydratedDocument`, otherwise `never`.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * type Virtuals = ExtractVirtualsType<HydratedDocument<MyDoc, MyVirtuals>>;
23
+ * // Virtuals is inferred as MyVirtuals
24
+ * ```
25
+ */
26
+ export type ExtractVirtualsType<T> = T extends HydratedDocument<any, infer U> ? U : never;
@@ -7,6 +7,7 @@ import {
7
7
  HydratedDocument,
8
8
  model,
9
9
  } from 'mongoose';
10
+ import mongooseLeanVirtuals from 'mongoose-lean-virtuals';
10
11
  import addressSchema, { AddressInstance, IAddress } from './embedded/address';
11
12
  import {
12
13
  toMap,
@@ -30,7 +31,7 @@ interface IUserDocumentOverrides {
30
31
  address: AddressInstance;
31
32
  }
32
33
 
33
- interface IUserVirtuals {
34
+ export interface IUserVirtuals {
34
35
  id: string;
35
36
  fullName: string;
36
37
  }
@@ -39,7 +40,8 @@ export type UserHydratedDocument = HydratedDocument<IUser, IUserDocumentOverride
39
40
 
40
41
  export type UserModelType = Model<
41
42
  IUser,
42
- ToMapQueryHelpers<UserHydratedDocument> & ToRecordsQueryHelpers<UserHydratedDocument>,
43
+ ToMapQueryHelpers<IUser, UserHydratedDocument, IUserVirtuals> &
44
+ ToRecordsQueryHelpers<IUser, UserHydratedDocument, IUserVirtuals>,
43
45
  IUserDocumentOverrides,
44
46
  IUserVirtuals,
45
47
  UserHydratedDocument
@@ -79,6 +81,7 @@ userSchema.virtual('fullName')
79
81
  return `${this.name} ${this.surname}`;
80
82
  });
81
83
 
84
+ userSchema.plugin(mongooseLeanVirtuals);
82
85
  userSchema.plugin(toMap);
83
86
  userSchema.plugin(toRecords);
84
87
 
@@ -1,4 +1,4 @@
1
- import User, { UserHydratedDocument } from './initializers/models/user';
1
+ import User, { IUser, IUserVirtuals, UserHydratedDocument } from './initializers/models/user';
2
2
 
3
3
  let user: UserHydratedDocument;
4
4
 
@@ -38,23 +38,15 @@ describe('toMap', () => {
38
38
  expect(users.get(user._id.toString())!).not.toBeInstanceOf(User);
39
39
  });
40
40
 
41
- it('should correctly handle a single document', async () => {
42
- const userFound = await User
43
- .findById(user._id)
44
- .toMap();
45
- expect(userFound).toBeTruthy();
46
- expect(userFound.has(user._id.toString())).toBe(true);
47
- expect(userFound.get(user._id.toString())!).toBeInstanceOf(User);
48
- });
49
-
50
- it('should correctly handle a single document with lean', async () => {
51
- const userFound = await User
52
- .findById(user._id)
53
- .lean()
41
+ it('should return a map with lean documents and virtuals', async () => {
42
+ const users = await User
43
+ .find()
44
+ .lean<(IUser & IUserVirtuals)[]>({ virtuals: true })
54
45
  .toMap();
55
- expect(userFound).toBeTruthy();
56
- expect(userFound.has(user._id.toString())).toBe(true);
57
- expect(userFound.get(user._id.toString())!).not.toBeInstanceOf(User);
46
+ expect(users).toBeTruthy();
47
+ expect(users.has(user._id.toString())).toBe(true);
48
+ expect(users.get(user._id.toString())!.fullName).toBeTruthy();
49
+ expect(users.get(user._id.toString())!).not.toBeInstanceOf(User);
58
50
  });
59
51
 
60
52
  it('should return an empty map if no documents are found', async () => {
@@ -84,21 +76,14 @@ describe('toRecords', () => {
84
76
  expect(users[user._id.toString()]).not.toBeInstanceOf(User);
85
77
  });
86
78
 
87
- it('should correctly handle a single document', async () => {
88
- const userFound = await User
89
- .findById(user._id)
90
- .toRecords();
91
- expect(userFound).toBeTruthy();
92
- expect(userFound[user._id.toString()]).toBeInstanceOf(User);
93
- });
94
-
95
- it('should correctly handle a single document with lean', async () => {
96
- const userFound = await User
97
- .findById(user._id)
98
- .lean()
79
+ it('should return a map with lean documents and virtuals', async () => {
80
+ const users = await User
81
+ .find()
82
+ .lean<(IUser & IUserVirtuals)[]>({ virtuals: true })
99
83
  .toRecords();
100
- expect(userFound).toBeTruthy();
101
- expect(userFound[user._id.toString()]).not.toBeInstanceOf(User);
84
+ expect(users).toBeTruthy();
85
+ expect(users[user._id.toString()].fullName).toBeTruthy();
86
+ expect(users[user._id.toString()]).not.toBeInstanceOf(User);
102
87
  });
103
88
 
104
89
  it('should return an empty map if no documents are found', async () => {