mongoose-utility-kit 0.0.1 → 0.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/.eslintignore ADDED
@@ -0,0 +1 @@
1
+ dist
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # mongoose-utility-kit
2
2
 
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 9bd9c4c: Added "toMap" and "toRecords" plugins. Added type "ExtractDocType".
8
+
3
9
  ## 0.0.1
4
10
 
5
11
  ### 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<MyModelHydratedDocument> & ToRecordsQueryHelpers<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,52 @@ 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
+ 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
+ var toMapPlugin = (schema) => {
45
+ schema.query.toMap = toMap;
46
+ };
47
+ var toMap_default = toMapPlugin;
48
+
49
+ // 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
+ var toRecordsPlugin = (schema) => {
67
+ schema.query.toRecords = toRecords;
68
+ };
69
+ var toRecords_default = toRecordsPlugin;
70
+
29
71
  // src/populated/functions.ts
30
72
  var import_mongoose = require("mongoose");
31
73
  var getPopulatedDocumentId = (populatedDocument) => {
@@ -68,5 +110,7 @@ var findOrReturnManyInstances = async (docOrIds, MongooseModel) => {
68
110
  0 && (module.exports = {
69
111
  findOrReturnInstance,
70
112
  findOrReturnManyInstances,
71
- getPopulatedDocumentId
113
+ getPopulatedDocumentId,
114
+ toMap,
115
+ toRecords
72
116
  });
package/dist/index.d.cts CHANGED
@@ -1,4 +1,55 @@
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<T extends HydratedDocument<any>> {
18
+ /**
19
+ * Converts the query results into a `Map` where the key is the document's _id.
20
+ *
21
+ * @returns A QueryWithHelpers instance that returns a `Map` of documents.
22
+ */
23
+ toMap(): QueryWithHelpers<Map<string, T>, T, ToMapQueryHelpers<T>, ExtractDocType<T>>;
24
+ }
25
+ /**
26
+ * Mongoose plugin to add the `toMap` method to queries.
27
+ *
28
+ * @template T The type of the `HydratedDocument`.
29
+ * @param schema The Mongoose schema to extend.
30
+ */
31
+ declare const toMapPlugin: <T extends unknown>(schema: Schema<any, any, any, ToMapQueryHelpers<T>, any, any, any>) => void;
32
+
33
+ /**
34
+ * Interface for query helpers that support converting results to a record (object).
35
+ *
36
+ * @template T The type of the `HydratedDocument`.
37
+ */
38
+ interface ToRecordsQueryHelpers<T extends HydratedDocument<any>> {
39
+ /**
40
+ * Converts the query results into a record (object) where the key is the document's _id.
41
+ *
42
+ * @returns A QueryWithHelpers instance that returns a Record of documents.
43
+ */
44
+ toRecords(): QueryWithHelpers<Record<string, T>, T, ToRecordsQueryHelpers<T>, ExtractDocType<T>>;
45
+ }
46
+ /**
47
+ * Mongoose plugin to add the `toRecords` method to queries.
48
+ *
49
+ * @template T The type of the `HydratedDocument`.
50
+ * @param schema The Mongoose schema to extend.
51
+ */
52
+ declare const toRecordsPlugin: <T extends unknown>(schema: Schema<any, any, any, ToRecordsQueryHelpers<T>, any, any, any>) => void;
2
53
 
3
54
  /**
4
55
  * Extracts the ID from a populated Mongoose document.
@@ -54,4 +105,4 @@ declare const findOrReturnInstance: <HydratedDocType extends Document>(docOrId:
54
105
  */
55
106
  declare const findOrReturnManyInstances: <HydratedDocType extends Document>(docOrIds: (HydratedDocType | Types.ObjectId)[], MongooseModel: Model<any, any, any, any, HydratedDocType>) => Promise<HydratedDocType[]>;
56
107
 
57
- export { findOrReturnInstance, findOrReturnManyInstances, getPopulatedDocumentId };
108
+ export { type ToMapQueryHelpers, type ToRecordsQueryHelpers, findOrReturnInstance, findOrReturnManyInstances, getPopulatedDocumentId, toMapPlugin as toMap, toRecordsPlugin as toRecords };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,55 @@
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<T extends HydratedDocument<any>> {
18
+ /**
19
+ * Converts the query results into a `Map` where the key is the document's _id.
20
+ *
21
+ * @returns A QueryWithHelpers instance that returns a `Map` of documents.
22
+ */
23
+ toMap(): QueryWithHelpers<Map<string, T>, T, ToMapQueryHelpers<T>, ExtractDocType<T>>;
24
+ }
25
+ /**
26
+ * Mongoose plugin to add the `toMap` method to queries.
27
+ *
28
+ * @template T The type of the `HydratedDocument`.
29
+ * @param schema The Mongoose schema to extend.
30
+ */
31
+ declare const toMapPlugin: <T extends unknown>(schema: Schema<any, any, any, ToMapQueryHelpers<T>, any, any, any>) => void;
32
+
33
+ /**
34
+ * Interface for query helpers that support converting results to a record (object).
35
+ *
36
+ * @template T The type of the `HydratedDocument`.
37
+ */
38
+ interface ToRecordsQueryHelpers<T extends HydratedDocument<any>> {
39
+ /**
40
+ * Converts the query results into a record (object) where the key is the document's _id.
41
+ *
42
+ * @returns A QueryWithHelpers instance that returns a Record of documents.
43
+ */
44
+ toRecords(): QueryWithHelpers<Record<string, T>, T, ToRecordsQueryHelpers<T>, ExtractDocType<T>>;
45
+ }
46
+ /**
47
+ * Mongoose plugin to add the `toRecords` method to queries.
48
+ *
49
+ * @template T The type of the `HydratedDocument`.
50
+ * @param schema The Mongoose schema to extend.
51
+ */
52
+ declare const toRecordsPlugin: <T extends unknown>(schema: Schema<any, any, any, ToRecordsQueryHelpers<T>, any, any, any>) => void;
2
53
 
3
54
  /**
4
55
  * Extracts the ID from a populated Mongoose document.
@@ -54,4 +105,4 @@ declare const findOrReturnInstance: <HydratedDocType extends Document>(docOrId:
54
105
  */
55
106
  declare const findOrReturnManyInstances: <HydratedDocType extends Document>(docOrIds: (HydratedDocType | Types.ObjectId)[], MongooseModel: Model<any, any, any, any, HydratedDocType>) => Promise<HydratedDocType[]>;
56
107
 
57
- export { findOrReturnInstance, findOrReturnManyInstances, getPopulatedDocumentId };
108
+ export { type ToMapQueryHelpers, type ToRecordsQueryHelpers, findOrReturnInstance, findOrReturnManyInstances, getPopulatedDocumentId, toMapPlugin as toMap, toRecordsPlugin as toRecords };
package/dist/index.js CHANGED
@@ -1,9 +1,48 @@
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
+ var toMapPlugin = (schema) => {
15
+ schema.query.toMap = toMap;
16
+ };
17
+ var toMap_default = toMapPlugin;
18
+
19
+ // 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
+ var toRecordsPlugin = (schema) => {
37
+ schema.query.toRecords = toRecords;
38
+ };
39
+ var toRecords_default = toRecordsPlugin;
40
+
1
41
  // src/populated/functions.ts
2
42
  import {
3
- Types,
4
- } from 'mongoose';
5
-
6
- const getPopulatedDocumentId = (populatedDocument) => {
43
+ Types
44
+ } from "mongoose";
45
+ var getPopulatedDocumentId = (populatedDocument) => {
7
46
  if (populatedDocument instanceof Types.ObjectId) {
8
47
  return populatedDocument.toString();
9
48
  }
@@ -11,21 +50,20 @@ const getPopulatedDocumentId = (populatedDocument) => {
11
50
  if (id) {
12
51
  return id.toString();
13
52
  }
14
- throw new Error('document incorrect');
53
+ throw new Error("document incorrect");
15
54
  };
16
- const findOrReturnInstance = async (docOrId, MongooseModel, err) => {
55
+ var findOrReturnInstance = async (docOrId, MongooseModel, err) => {
17
56
  if (docOrId instanceof MongooseModel) {
18
57
  return docOrId;
19
58
  }
20
59
  const result = await MongooseModel.findById(docOrId).orFail(err);
21
60
  return result;
22
61
  };
23
- const findOrReturnManyInstances = async (docOrIds, MongooseModel) => {
62
+ var findOrReturnManyInstances = async (docOrIds, MongooseModel) => {
24
63
  const [result, objectIds] = docOrIds.reduce((acc, docOrId) => {
25
64
  if (docOrId instanceof MongooseModel) {
26
65
  acc[0].push(docOrId);
27
- }
28
- else if (docOrId instanceof Types.ObjectId) {
66
+ } else if (docOrId instanceof Types.ObjectId) {
29
67
  acc[1].push(docOrId);
30
68
  }
31
69
  return acc;
@@ -33,8 +71,8 @@ const findOrReturnManyInstances = async (docOrIds, MongooseModel) => {
33
71
  if (objectIds.length > 0) {
34
72
  const docs = await MongooseModel.find({
35
73
  _id: {
36
- $in: objectIds,
37
- },
74
+ $in: objectIds
75
+ }
38
76
  });
39
77
  result.push(...docs);
40
78
  }
@@ -44,4 +82,6 @@ export {
44
82
  findOrReturnInstance,
45
83
  findOrReturnManyInstances,
46
84
  getPopulatedDocumentId,
85
+ toMap_default as toMap,
86
+ toRecords_default as toRecords
47
87
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mongoose-utility-kit",
3
- "version": "0.0.1",
3
+ "version": "0.1.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,63 @@
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 `Map`.
6
+ *
7
+ * @template T The type of the `HydratedDocument`.
8
+ */
9
+ export interface ToMapQueryHelpers<T extends HydratedDocument<any>> {
10
+ /**
11
+ * Converts the query results into a `Map` where the key is the document's _id.
12
+ *
13
+ * @returns A QueryWithHelpers instance that returns a `Map` of documents.
14
+ */
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;
48
+ }
49
+
50
+ /**
51
+ * Mongoose plugin to add the `toMap` method to queries.
52
+ *
53
+ * @template T The type of the `HydratedDocument`.
54
+ * @param schema The Mongoose schema to extend.
55
+ */
56
+ const toMapPlugin = <T extends HydratedDocument<any>>(
57
+ schema: Schema<any, any, any, ToMapQueryHelpers<T>, any, any, any>,
58
+ ) => {
59
+ // eslint-disable-next-line no-param-reassign
60
+ schema.query.toMap = toMap;
61
+ };
62
+
63
+ export default toMapPlugin;
@@ -0,0 +1,67 @@
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<T extends HydratedDocument<any>> {
10
+ /**
11
+ * Converts the query results into a record (object) where the key is the document's _id.
12
+ *
13
+ * @returns A QueryWithHelpers instance that returns a Record of documents.
14
+ */
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;
52
+ }
53
+
54
+ /**
55
+ * Mongoose plugin to add the `toRecords` method to queries.
56
+ *
57
+ * @template T The type of the `HydratedDocument`.
58
+ * @param schema The Mongoose schema to extend.
59
+ */
60
+ const toRecordsPlugin = <T extends HydratedDocument<any>>(
61
+ schema: Schema<any, any, any, ToRecordsQueryHelpers<T>, any, any, any>,
62
+ ) => {
63
+ // eslint-disable-next-line no-param-reassign
64
+ schema.query.toRecords = toRecords;
65
+ };
66
+
67
+ 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,7 @@ export type UserHydratedDocument = HydratedDocument<IUser, IUserDocumentOverride
33
39
 
34
40
  export type UserModelType = Model<
35
41
  IUser,
36
- {},
42
+ ToMapQueryHelpers<UserHydratedDocument> & ToRecordsQueryHelpers<UserHydratedDocument>,
37
43
  IUserDocumentOverrides,
38
44
  IUserVirtuals,
39
45
  UserHydratedDocument
@@ -73,4 +79,9 @@ userSchema.virtual('fullName')
73
79
  return `${this.name} ${this.surname}`;
74
80
  });
75
81
 
76
- export default model<IUser, UserModelType>('User', userSchema);
82
+ userSchema.plugin(toMap);
83
+ userSchema.plugin(toRecords);
84
+
85
+ const User = model<IUser, UserModelType>('User', userSchema);
86
+
87
+ export default User;
@@ -0,0 +1,111 @@
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 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()
54
+ .toMap();
55
+ expect(userFound).toBeTruthy();
56
+ expect(userFound.has(user._id.toString())).toBe(true);
57
+ expect(userFound.get(user._id.toString())!).not.toBeInstanceOf(User);
58
+ });
59
+
60
+ it('should return an empty map if no documents are found', async () => {
61
+ const users = await User
62
+ .find({ email: 'non-existent@email.com' })
63
+ .toMap();
64
+ expect(users).toBeTruthy();
65
+ expect(users.size).toBe(0);
66
+ });
67
+ });
68
+
69
+ describe('toRecords', () => {
70
+ it('should return a map with the found documents', async () => {
71
+ const users = await User
72
+ .find()
73
+ .toRecords();
74
+ expect(users).toBeTruthy();
75
+ expect(users[user.id]).toBeInstanceOf(User);
76
+ });
77
+
78
+ it('should return a map with lean documents', async () => {
79
+ const users = await User
80
+ .find()
81
+ .lean()
82
+ .toRecords();
83
+ expect(users).toBeTruthy();
84
+ expect(users[user._id.toString()]).not.toBeInstanceOf(User);
85
+ });
86
+
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()
99
+ .toRecords();
100
+ expect(userFound).toBeTruthy();
101
+ expect(userFound[user._id.toString()]).not.toBeInstanceOf(User);
102
+ });
103
+
104
+ it('should return an empty map if no documents are found', async () => {
105
+ const users = await User
106
+ .find({ email: 'non-existent@email.com' })
107
+ .toRecords();
108
+ expect(users).toBeTruthy();
109
+ expect(Object.keys(users)).toHaveLength(0);
110
+ });
111
+ });
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
  });