mongoose-utility-kit 0.2.0 → 0.4.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.
@@ -14,16 +14,30 @@ jobs:
14
14
  ci:
15
15
  runs-on: ubuntu-latest
16
16
 
17
+ strategy:
18
+ fail-fast: false
19
+ matrix:
20
+ node-version: [18, 20, 22, 24]
21
+ mongoose-version: [8, 9]
22
+ exclude:
23
+ - node-version: 18
24
+ mongoose-version: 9
25
+
26
+ name: Node ${{ matrix.node-version }} / Mongoose ${{ matrix.mongoose-version }}
27
+
17
28
  steps:
18
29
  - uses: actions/checkout@v4
19
30
 
20
- - name: Use Node.js
31
+ - name: Use Node.js ${{ matrix.node-version }}
21
32
  uses: actions/setup-node@v4
22
33
  with:
23
- node-version: "20"
34
+ node-version: ${{ matrix.node-version }}
24
35
 
25
36
  - name: Install dependencies
26
37
  run: yarn
27
38
 
39
+ - name: Install mongoose ${{ matrix.mongoose-version }}
40
+ run: yarn add --dev mongoose@${{ matrix.mongoose-version }}
41
+
28
42
  - name: Run CI
29
43
  run: yarn ci
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # mongoose-utility-kit
2
2
 
3
+ ## 0.4.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 2d3c352: Added new utility functions: isPopulated, ensurePopulated, toObjectId, areIdsEqual.
8
+
9
+ ## 0.3.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 794bd55: added overload type of toMap & toRecords to handle virtuals
14
+
3
15
  ## 0.2.0
4
16
 
5
17
  ### Minor Changes
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # mongoose-utility-kit 🛠️
1
+ # mongoose-utility-kit
2
2
 
3
3
  A set of utility functions and plugins to simplify common `mongoose` operations. Designed for `TypeScript` and `mongoose` projects with strict type safety.
4
4
 
@@ -8,7 +8,7 @@ A set of utility functions and plugins to simplify common `mongoose` operations.
8
8
 
9
9
  - **Type-safe**: Built with TypeScript for robust type checking.
10
10
  - **Efficient**: Reduces redundant database queries and simplifies data transformations.
11
- - **Flexible**: Handles both document instances and ObjectIds seamlessly.
11
+ - **Flexible**: Handles documents, ObjectIds, and string IDs seamlessly.
12
12
  - **Population Ready**: Designed for mongoose documents with populated references.
13
13
  - **Data Transformation**: Provides plugins to convert query results into `Map` or `Record` objects.
14
14
 
@@ -41,9 +41,9 @@ export interface IUser {
41
41
  email: string;
42
42
  }
43
43
 
44
- export interface IUserDocumentOverrides = { /* ... */ }
44
+ export interface IUserDocumentOverrides { /* ... */ }
45
45
 
46
- export interface IUserVirtuals = { /* ... */ }
46
+ export interface IUserVirtuals { /* ... */ }
47
47
 
48
48
  export type UserHydratedDocument = HydratedDocument<IUser, IUserDocumentOverrides & IUserVirtuals>;
49
49
  ```
@@ -65,9 +65,44 @@ export interface IComment {
65
65
 
66
66
  ### Utility Functions
67
67
 
68
- #### 1. `getPopulatedDocumentId`
68
+ #### `isPopulated`
69
69
 
70
- Handle both populated documents and ObjectIds safely:
70
+ Type guard to check if a `PopulatedDoc` field is a populated document or an ObjectId:
71
+
72
+ ```ts
73
+ import { isPopulated } from "mongoose-utility-kit";
74
+
75
+ const comment = await Comment.findById(someId).orFail();
76
+
77
+ if (isPopulated(comment.user)) {
78
+ // TypeScript knows comment.user is UserHydratedDocument
79
+ console.log(comment.user.name);
80
+ } else {
81
+ // comment.user is an ObjectId
82
+ console.log(comment.user.toString());
83
+ }
84
+ ```
85
+
86
+ #### `ensurePopulated`
87
+
88
+ Assertion version of `isPopulated`. Returns the populated document or throws if the field is not populated:
89
+
90
+ ```ts
91
+ import { ensurePopulated } from "mongoose-utility-kit";
92
+
93
+ const comment = await Comment.findById(someId).populate("user").orFail();
94
+ const user = ensurePopulated(comment.user);
95
+ // TypeScript knows user is UserHydratedDocument
96
+ console.log(user.name);
97
+
98
+ // Without population — throws Error
99
+ const comment2 = await Comment.findById(someId).orFail();
100
+ ensurePopulated(comment2.user); // Error: Expected a populated document
101
+ ```
102
+
103
+ #### `getPopulatedDocumentId`
104
+
105
+ Extract the `_id` as a string from a field that may or may not be populated:
71
106
 
72
107
  ```ts
73
108
  import { getPopulatedDocumentId } from "mongoose-utility-kit";
@@ -83,32 +118,81 @@ const comment = await Comment.findById(someId)
83
118
  getPopulatedDocumentId(comment.user); // '507f191e810c19729de860ea'
84
119
  ```
85
120
 
86
- #### 2. `findOrReturnInstance`
121
+ #### `toObjectId`
122
+
123
+ Convert a string, ObjectId, or Document to a `Types.ObjectId`:
124
+
125
+ ```ts
126
+ import { toObjectId } from "mongoose-utility-kit";
127
+
128
+ // From an ObjectId — returns as-is
129
+ toObjectId(someObjectId);
130
+
131
+ // From a string — constructs a new ObjectId
132
+ toObjectId("507f191e810c19729de860ea");
133
+
134
+ // From a Document — extracts _id
135
+ toObjectId(userDocument);
136
+
137
+ // Throws on invalid string
138
+ toObjectId("invalid"); // Error!
139
+ ```
140
+
141
+ #### `areIdsEqual`
142
+
143
+ Compare two values by their underlying MongoDB ID. Accepts strings, ObjectIds, Documents, and populated documents. Returns `false` for `null` or `undefined`:
144
+
145
+ ```ts
146
+ import { areIdsEqual } from "mongoose-utility-kit";
147
+
148
+ areIdsEqual(user._id, comment.user); // true (ObjectId vs PopulatedDoc)
149
+ areIdsEqual(user, "507f191e810c19729de860ea"); // true (Document vs string)
150
+ areIdsEqual(user._id, otherUser._id); // false
151
+ areIdsEqual(null, user._id); // false
152
+ ```
153
+
154
+ #### `findOrReturnInstance`
155
+
156
+ Avoid redundant queries: returns the document if already hydrated, otherwise fetches it by ID. Accepts ObjectIds and string IDs:
87
157
 
88
158
  ```ts
89
159
  import { findOrReturnInstance } from "mongoose-utility-kit";
90
160
 
91
- // With ObjectId reference
92
- const comment = await Comment.findById(someId).orFail();
93
- findOrReturnInstance(comment.user, UserModel);
161
+ // With ObjectId — fetches from DB
162
+ const user = await findOrReturnInstance(comment.user, UserModel);
94
163
 
95
- // With populated document
96
- const comment = await Comment.findById(someId)
97
- .populate<{ user: UserHydratedDocument }>("user")
98
- .orFail();
99
- findOrReturnInstance(comment.user, UserModel);
164
+ // With string ID — fetches from DB
165
+ const user = await findOrReturnInstance("507f191e810c19729de860ea", UserModel);
166
+
167
+ // With populated document — returns it directly, no DB query
168
+ const user = await findOrReturnInstance(comment.user, UserModel);
169
+
170
+ // With custom error
171
+ const user = await findOrReturnInstance(
172
+ someId,
173
+ UserModel,
174
+ new Error("User not found"),
175
+ );
176
+
177
+ // With error factory
178
+ const user = await findOrReturnInstance(
179
+ someId,
180
+ UserModel,
181
+ () => new Error("User not found"),
182
+ );
100
183
  ```
101
184
 
102
- #### 3. `findOrReturnManyInstances`
185
+ #### `findOrReturnManyInstances`
186
+
187
+ Batch version of `findOrReturnInstance`. Separates already-hydrated documents from IDs, performs a single `$in` query for the missing ones, and returns the combined result. Accepts ObjectIds and string IDs:
103
188
 
104
189
  ```ts
105
190
  import { findOrReturnManyInstances } from "mongoose-utility-kit";
106
- import { UserHydratedDocument } from "./user";
107
- import { Types } from "mongoose";
108
191
 
109
- const inputs: (UserHydratedDocument | Types.ObjectId)[] = [
110
- existingUserDocument,
111
- new Types.ObjectId(),
192
+ const inputs = [
193
+ existingUserDocument, // already hydrated — no query needed
194
+ new Types.ObjectId("..."), // ObjectId — will be fetched
195
+ "507f191e810c19729de860ea", // string ID — will be fetched
112
196
  ];
113
197
 
114
198
  const users = await findOrReturnManyInstances(inputs, UserModel);
@@ -116,36 +200,38 @@ const users = await findOrReturnManyInstances(inputs, UserModel);
116
200
 
117
201
  ### Mongoose Plugins
118
202
 
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
203
+ These plugins add query helpers that transform results into `Map` or `Record` objects, keyed by `_id`.
122
204
 
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.
205
+ - **toMap()**: Returns a `Map<string, Document>`.
206
+ - **toRecords()**: Returns a `Record<string, Document>` (plain object).
125
207
 
126
208
  #### Integration
127
209
 
128
- 1. Import the plugins:
210
+ 1. Import the plugins and type helpers:
129
211
 
130
212
  ```ts
131
- import { toMap, toRecords } from "mongoose-utility-kit";
213
+ import {
214
+ toMap, ToMapQueryHelpers,
215
+ toRecords, ToRecordsQueryHelpers,
216
+ } from "mongoose-utility-kit";
132
217
  ```
133
218
 
134
- 2. Register the plugins with your schema:
219
+ 2. Register the plugins with your schema:
135
220
 
136
221
  ```ts
137
222
  type MyModelHydratedDocument = HydratedDocument<IMyModel>;
138
223
 
224
+ // TVirtuals defaults to {}, so it can be omitted when not using virtuals
139
225
  type MyModelType = Model<
140
226
  IMyModel,
141
- ToMapQueryHelpers<IMyModel, MyModelHydratedDocument> & ToRecordsQueryHelpers<IMyModel, MyModelHydratedDocument>,
227
+ ToMapQueryHelpers<IMyModel, MyModelHydratedDocument> &
228
+ ToRecordsQueryHelpers<IMyModel, MyModelHydratedDocument>,
142
229
  {},
143
230
  {},
144
231
  MyModelHydratedDocument
145
232
  >;
146
233
 
147
234
  const schema = new mongoose.Schema<IMyModel, MyModelType>({
148
- // Define your schema here
149
235
  name: String,
150
236
  value: Number,
151
237
  });
@@ -156,17 +242,56 @@ These plugins provide helper methods for Mongoose queries to transform the resul
156
242
  const MyModel = mongoose.model<IMyModel, MyModelType>("MyModel", schema);
157
243
  ```
158
244
 
245
+ With virtuals, pass the virtuals type as the third generic parameter:
246
+
247
+ ```ts
248
+ ToMapQueryHelpers<IMyModel, MyModelHydratedDocument, IMyModelVirtuals>
249
+ ```
250
+
159
251
  #### Examples
160
252
 
161
253
  ```ts
162
254
  // Converts the query result to a Map
163
- const myMap = await MyModel.find({}).toMap(); // new Map<string, MyModel>
255
+ const myMap = await MyModel.find({}).toMap();
256
+ // Map<string, MyModelHydratedDocument>
164
257
 
165
258
  // Converts the query result to a Record
166
- const myRecords = await MyModel.find({}).toRecords(); // Record<string, MyModel>
259
+ const myRecords = await MyModel.find({}).toRecords();
260
+ // Record<string, MyModelHydratedDocument>
261
+
262
+ // Works with lean queries
263
+ const leanMap = await MyModel.find({}).lean().toMap();
264
+ // Map<string, IMyModel>
265
+
266
+ // Works with lean queries + virtuals
267
+ const leanMap = await MyModel.find({})
268
+ .lean<(IMyModel & IMyModelVirtuals)[]>({ virtuals: true })
269
+ .toMap();
270
+ // Map<string, IMyModel & IMyModelVirtuals>
271
+ ```
272
+
273
+ ## API Reference
274
+
275
+ ### `isPopulated`
276
+
277
+ ```ts
278
+ function isPopulated<HydratedDocType extends Document>(
279
+ value: PopulatedDoc<HydratedDocType>
280
+ ): value is HydratedDocType;
281
+ ```
282
+
283
+ **Returns:** `true` if the value is a populated document, `false` if it's an ObjectId, `null`, or `undefined`.
284
+
285
+ ### `ensurePopulated`
286
+
287
+ ```ts
288
+ function ensurePopulated<HydratedDocType extends Document>(
289
+ value: PopulatedDoc<HydratedDocType>
290
+ ): HydratedDocType;
167
291
  ```
168
292
 
169
- ## API Documentation
293
+ **Returns:** The populated document with its type narrowed.
294
+ **Throws:** `Error` if the value is not a populated document.
170
295
 
171
296
  ### `getPopulatedDocumentId`
172
297
 
@@ -176,30 +301,66 @@ function getPopulatedDocumentId<HydratedDocType extends Document>(
176
301
  ): string;
177
302
  ```
178
303
 
179
- **Handles:** Both populated documents and raw ObjectIds
180
- **Throws:** If no valid ID found (`Error('document incorrect')`)
304
+ **Handles:** Both populated documents and raw ObjectIds.
305
+ **Throws:** `Error` if the value has no valid `_id`.
306
+
307
+ ### `toObjectId`
308
+
309
+ ```ts
310
+ function toObjectId(
311
+ value: string | Types.ObjectId | Document
312
+ ): Types.ObjectId;
313
+ ```
314
+
315
+ **Returns:** A `Types.ObjectId`.
316
+ **Throws:** `Error` if a string value is not a valid 24-character hex ObjectId.
317
+
318
+ ### `areIdsEqual`
319
+
320
+ ```ts
321
+ function areIdsEqual(
322
+ a: string | Types.ObjectId | Document | PopulatedDoc<any> | null | undefined,
323
+ b: string | Types.ObjectId | Document | PopulatedDoc<any> | null | undefined
324
+ ): boolean;
325
+ ```
326
+
327
+ **Returns:** `true` if both values resolve to the same ID string. Returns `false` if either value is `null` or `undefined`.
181
328
 
182
329
  ### `findOrReturnInstance`
183
330
 
184
331
  ```ts
185
332
  async function findOrReturnInstance<HydratedDocType extends Document>(
186
- docOrId: HydratedDocType | Types.ObjectId,
333
+ docOrId: HydratedDocType | Types.ObjectId | string,
187
334
  MongooseModel: Model<any, any, any, any, HydratedDocType>,
188
335
  err?: Error | (() => Error)
189
336
  ): Promise<HydratedDocType>;
190
337
  ```
191
338
 
192
- **Throws:** Default error or custom error if document not found
339
+ **Throws:** Default error or custom error if document not found.
193
340
 
194
341
  ### `findOrReturnManyInstances`
195
342
 
196
343
  ```ts
197
344
  async function findOrReturnManyInstances<HydratedDocType extends Document>(
198
- docOrIds: (HydratedDocType | Types.ObjectId)[],
345
+ docOrIds: (HydratedDocType | Types.ObjectId | string)[],
199
346
  MongooseModel: Model<any, any, any, any, HydratedDocType>
200
347
  ): Promise<HydratedDocType[]>;
201
348
  ```
202
349
 
350
+ > **Note:** Non-existent IDs are silently omitted from the result (consistent with `find({ _id: { $in: [...] } })` behavior). String IDs are converted to ObjectIds internally.
351
+
352
+ ### `ToMapQueryHelpers`
353
+
354
+ ```ts
355
+ interface ToMapQueryHelpers<RawDocType, HydratedDocType, TVirtuals = {}> { ... }
356
+ ```
357
+
358
+ ### `ToRecordsQueryHelpers`
359
+
360
+ ```ts
361
+ interface ToRecordsQueryHelpers<RawDocType, HydratedDocType, TVirtuals = {}> { ... }
362
+ ```
363
+
203
364
  ## Development
204
365
 
205
366
  ```sh
@@ -210,9 +371,9 @@ Tests use `mongodb-memory-server` for in-memory MongoDB testing.
210
371
 
211
372
  ## Compatibility
212
373
 
213
- - mongoose 8.x+
214
- - TypeScript 4.5+
215
- - Node.js 16+
374
+ - mongoose 8.x / 9.x
375
+ - TypeScript 5.0+
376
+ - Node.js 18+
216
377
 
217
378
  ## License
218
379
 
package/dist/index.cjs CHANGED
@@ -20,10 +20,14 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ areIdsEqual: () => areIdsEqual,
24
+ ensurePopulated: () => ensurePopulated,
23
25
  findOrReturnInstance: () => findOrReturnInstance,
24
26
  findOrReturnManyInstances: () => findOrReturnManyInstances,
25
27
  getPopulatedDocumentId: () => getPopulatedDocumentId,
28
+ isPopulated: () => isPopulated,
26
29
  toMap: () => toMap_default,
30
+ toObjectId: () => toObjectId,
27
31
  toRecords: () => toRecords_default
28
32
  });
29
33
  module.exports = __toCommonJS(index_exports);
@@ -70,11 +74,11 @@ var getPopulatedDocumentId = (populatedDocument) => {
70
74
  if (populatedDocument instanceof import_mongoose.Types.ObjectId) {
71
75
  return populatedDocument.toString();
72
76
  }
73
- const id = populatedDocument?.id || populatedDocument?._id;
74
- if (id) {
75
- return id.toString();
77
+ const _id = populatedDocument?._id;
78
+ if (_id) {
79
+ return _id.toString();
76
80
  }
77
- throw new Error("document incorrect");
81
+ throw new Error(`Expected a populated document or ObjectId, got: ${typeof populatedDocument}`);
78
82
  };
79
83
  var findOrReturnInstance = async (docOrId, MongooseModel, err) => {
80
84
  if (docOrId instanceof MongooseModel) {
@@ -89,6 +93,8 @@ var findOrReturnManyInstances = async (docOrIds, MongooseModel) => {
89
93
  acc[0].push(docOrId);
90
94
  } else if (docOrId instanceof import_mongoose.Types.ObjectId) {
91
95
  acc[1].push(docOrId);
96
+ } else if (typeof docOrId === "string") {
97
+ acc[1].push(new import_mongoose.Types.ObjectId(docOrId));
92
98
  }
93
99
  return acc;
94
100
  }, [[], []]);
@@ -102,11 +108,57 @@ var findOrReturnManyInstances = async (docOrIds, MongooseModel) => {
102
108
  }
103
109
  return result;
104
110
  };
111
+ var isPopulated = (value) => {
112
+ if (value instanceof import_mongoose.Types.ObjectId) {
113
+ return false;
114
+ }
115
+ if (value != null && typeof value === "object" && ("_id" in value || "id" in value)) {
116
+ return true;
117
+ }
118
+ return false;
119
+ };
120
+ var toObjectId = (value) => {
121
+ if (value instanceof import_mongoose.Types.ObjectId) {
122
+ return value;
123
+ }
124
+ if (typeof value === "object" && value !== null && "_id" in value) {
125
+ return value._id;
126
+ }
127
+ return new import_mongoose.Types.ObjectId(value);
128
+ };
129
+ var areIdsEqual = (a, b) => {
130
+ if (a == null || b == null) {
131
+ return false;
132
+ }
133
+ const normalize = (val) => {
134
+ if (typeof val === "string") {
135
+ return val;
136
+ }
137
+ if (val instanceof import_mongoose.Types.ObjectId) {
138
+ return val.toString();
139
+ }
140
+ if (typeof val === "object" && "_id" in val) {
141
+ return val._id.toString();
142
+ }
143
+ return String(val);
144
+ };
145
+ return normalize(a) === normalize(b);
146
+ };
147
+ var ensurePopulated = (value) => {
148
+ if (isPopulated(value)) {
149
+ return value;
150
+ }
151
+ throw new Error(`Expected a populated document, got: ${typeof value}`);
152
+ };
105
153
  // Annotate the CommonJS export names for ESM import in node:
106
154
  0 && (module.exports = {
155
+ areIdsEqual,
156
+ ensurePopulated,
107
157
  findOrReturnInstance,
108
158
  findOrReturnManyInstances,
109
159
  getPopulatedDocumentId,
160
+ isPopulated,
110
161
  toMap,
162
+ toObjectId,
111
163
  toRecords
112
164
  });