mongoose-utility-kit 0.3.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,11 @@
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
+
3
9
  ## 0.3.0
4
10
 
5
11
  ### 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
  });
package/dist/index.d.cts CHANGED
@@ -29,7 +29,7 @@ type ExtractVirtualsType<T> = T extends HydratedDocument<any, infer U> ? U : nev
29
29
  *
30
30
  * @template T The type of the `HydratedDocument`.
31
31
  */
32
- interface ToMapQueryHelpers<RawDocType, HydratedDocType, TVirtuals> {
32
+ interface ToMapQueryHelpers<RawDocType, HydratedDocType, TVirtuals = {}> {
33
33
  /**
34
34
  * Query helper interface for converting query results into a `Map` keyed by string,
35
35
  * including virtual properties.
@@ -98,7 +98,7 @@ declare const toMapPlugin: <T extends unknown>(schema: Schema<any, any, any, ToM
98
98
  *
99
99
  * @template T The type of the `HydratedDocument`.
100
100
  */
101
- interface ToRecordsQueryHelpers<RawDocType, HydratedDocType, TVirtuals> {
101
+ interface ToRecordsQueryHelpers<RawDocType, HydratedDocType, TVirtuals = {}> {
102
102
  /**
103
103
  * Query helper for transforming query results into a `Record<string, T>` object,
104
104
  * including virtual properties.
@@ -186,7 +186,8 @@ declare const getPopulatedDocumentId: <HydratedDocType extends Document>(populat
186
186
  * through the `err` parameter.
187
187
  *
188
188
  * @template HydratedDocType - The type of the hydrated document, extending `Document`.
189
- * @param {HydratedDocType | Types.ObjectId} docOrId - The document instance or ObjectId to find.
189
+ * @param {HydratedDocType | Types.ObjectId | string} docOrId
190
+ * - The document instance, ObjectId, or string ID to find.
190
191
  * @param {Model<any, any, any, any, HydratedDocType>} MongooseModel
191
192
  * - The Mongoose model used to query the database.
192
193
  * @param {Error | (() => Error)} [err]
@@ -194,7 +195,7 @@ declare const getPopulatedDocumentId: <HydratedDocType extends Document>(populat
194
195
  * @returns {Promise<HydratedDocType>} A promise that resolves to the hydrated document instance.
195
196
  * @throws {Error} - Throws an error if the document is not found and no custom error is provided.
196
197
  */
197
- declare const findOrReturnInstance: <HydratedDocType extends Document>(docOrId: HydratedDocType | Types.ObjectId, MongooseModel: Model<any, any, any, any, HydratedDocType>, err?: Error | (() => Error)) => Promise<HydratedDocType>;
198
+ declare const findOrReturnInstance: <HydratedDocType extends Document>(docOrId: HydratedDocType | Types.ObjectId | string, MongooseModel: Model<any, any, any, any, HydratedDocType>, err?: Error | (() => Error)) => Promise<HydratedDocType>;
198
199
  /**
199
200
  * Finds multiple Mongoose documents by their IDs or returns the provided instances.
200
201
  *
@@ -206,13 +207,65 @@ declare const findOrReturnInstance: <HydratedDocType extends Document>(docOrId:
206
207
  * that are not already represented by instances.
207
208
  *
208
209
  * @template HydratedDocType - The type of the hydrated documents, extending `Document`.
209
- * @param {(HydratedDocType | Types.ObjectId)[]} docOrIds
210
- * - An array of document instances or ObjectIds to find.
210
+ * @param {(HydratedDocType | Types.ObjectId | string)[]} docOrIds
211
+ * - An array of document instances, ObjectIds, or string IDs to find.
211
212
  * @param {Model<any, any, any, any, HydratedDocType>} MongooseModel
212
213
  * - The Mongoose model used to query the database.
213
214
  * @returns {Promise<HydratedDocType[]>}
214
215
  * A promise that resolves to an array of hydrated document instances.
215
216
  */
216
- declare const findOrReturnManyInstances: <HydratedDocType extends Document>(docOrIds: (HydratedDocType | Types.ObjectId)[], MongooseModel: Model<any, any, any, any, HydratedDocType>) => Promise<HydratedDocType[]>;
217
+ declare const findOrReturnManyInstances: <HydratedDocType extends Document>(docOrIds: (HydratedDocType | Types.ObjectId | string)[], MongooseModel: Model<any, any, any, any, HydratedDocType>) => Promise<HydratedDocType[]>;
218
+ /**
219
+ * Type guard that checks if a potentially populated Mongoose field
220
+ * is actually a populated document rather than an ObjectId.
221
+ *
222
+ * This is useful for narrowing the type of a `PopulatedDoc<HydratedDocType>`
223
+ * field after conditionally populating a query.
224
+ *
225
+ * @template HydratedDocType - The type of the populated document, extending `Document`.
226
+ * @param {PopulatedDoc<HydratedDocType>} value
227
+ * - The value to check, which may be either a populated document or an ObjectId.
228
+ * @returns {value is HydratedDocType} `true` if the value is a populated document.
229
+ */
230
+ declare const isPopulated: <HydratedDocType extends Document>(value: PopulatedDoc<HydratedDocType>) => value is HydratedDocType;
231
+ /**
232
+ * Converts a string, ObjectId, or Document to a `Types.ObjectId`.
233
+ *
234
+ * If the value is already an `ObjectId`, it is returned as-is.
235
+ * If the value is a Document, its `_id` is returned.
236
+ * If the value is a string, a new `Types.ObjectId` is constructed from it.
237
+ *
238
+ * @param {string | Types.ObjectId | Document} value - The value to convert.
239
+ * @returns {Types.ObjectId} The resulting ObjectId.
240
+ * @throws {Error} If the string is not a valid 24-character hex string.
241
+ */
242
+ declare const toObjectId: (value: string | Types.ObjectId | Document) => Types.ObjectId;
243
+ /**
244
+ * Compares two values by their underlying MongoDB document ID.
245
+ *
246
+ * Each value can be a string, `ObjectId`, `Document`, or `PopulatedDoc`.
247
+ * Returns `false` if either value is `null` or `undefined`.
248
+ *
249
+ * @param {string | Types.ObjectId | Document | PopulatedDoc<any> | null | undefined} a
250
+ * - The first value to compare.
251
+ * @param {string | Types.ObjectId | Document | PopulatedDoc<any> | null | undefined} b
252
+ * - The second value to compare.
253
+ * @returns {boolean} `true` if both values resolve to the same ID string.
254
+ */
255
+ declare const areIdsEqual: (a: string | Types.ObjectId | Document | PopulatedDoc<any> | null | undefined, b: string | Types.ObjectId | Document | PopulatedDoc<any> | null | undefined) => boolean;
256
+ /**
257
+ * Asserts that a potentially populated Mongoose field is actually a populated document.
258
+ *
259
+ * This is the assertion counterpart of `isPopulated`. If the value is not populated,
260
+ * an error is thrown. Otherwise, the value is returned with its type narrowed to
261
+ * `HydratedDocType`.
262
+ *
263
+ * @template HydratedDocType - The type of the populated document, extending `Document`.
264
+ * @param {PopulatedDoc<HydratedDocType>} value
265
+ * - The value to check, which may be either a populated document or an ObjectId.
266
+ * @returns {HydratedDocType} The populated document.
267
+ * @throws {Error} If the value is not a populated document.
268
+ */
269
+ declare const ensurePopulated: <HydratedDocType extends Document>(value: PopulatedDoc<HydratedDocType>) => HydratedDocType;
217
270
 
218
- export { type ToMapQueryHelpers, type ToRecordsQueryHelpers, findOrReturnInstance, findOrReturnManyInstances, getPopulatedDocumentId, toMapPlugin as toMap, toRecordsPlugin as toRecords };
271
+ export { type ToMapQueryHelpers, type ToRecordsQueryHelpers, areIdsEqual, ensurePopulated, findOrReturnInstance, findOrReturnManyInstances, getPopulatedDocumentId, isPopulated, toMapPlugin as toMap, toObjectId, toRecordsPlugin as toRecords };
package/dist/index.d.ts CHANGED
@@ -29,7 +29,7 @@ type ExtractVirtualsType<T> = T extends HydratedDocument<any, infer U> ? U : nev
29
29
  *
30
30
  * @template T The type of the `HydratedDocument`.
31
31
  */
32
- interface ToMapQueryHelpers<RawDocType, HydratedDocType, TVirtuals> {
32
+ interface ToMapQueryHelpers<RawDocType, HydratedDocType, TVirtuals = {}> {
33
33
  /**
34
34
  * Query helper interface for converting query results into a `Map` keyed by string,
35
35
  * including virtual properties.
@@ -98,7 +98,7 @@ declare const toMapPlugin: <T extends unknown>(schema: Schema<any, any, any, ToM
98
98
  *
99
99
  * @template T The type of the `HydratedDocument`.
100
100
  */
101
- interface ToRecordsQueryHelpers<RawDocType, HydratedDocType, TVirtuals> {
101
+ interface ToRecordsQueryHelpers<RawDocType, HydratedDocType, TVirtuals = {}> {
102
102
  /**
103
103
  * Query helper for transforming query results into a `Record<string, T>` object,
104
104
  * including virtual properties.
@@ -186,7 +186,8 @@ declare const getPopulatedDocumentId: <HydratedDocType extends Document>(populat
186
186
  * through the `err` parameter.
187
187
  *
188
188
  * @template HydratedDocType - The type of the hydrated document, extending `Document`.
189
- * @param {HydratedDocType | Types.ObjectId} docOrId - The document instance or ObjectId to find.
189
+ * @param {HydratedDocType | Types.ObjectId | string} docOrId
190
+ * - The document instance, ObjectId, or string ID to find.
190
191
  * @param {Model<any, any, any, any, HydratedDocType>} MongooseModel
191
192
  * - The Mongoose model used to query the database.
192
193
  * @param {Error | (() => Error)} [err]
@@ -194,7 +195,7 @@ declare const getPopulatedDocumentId: <HydratedDocType extends Document>(populat
194
195
  * @returns {Promise<HydratedDocType>} A promise that resolves to the hydrated document instance.
195
196
  * @throws {Error} - Throws an error if the document is not found and no custom error is provided.
196
197
  */
197
- declare const findOrReturnInstance: <HydratedDocType extends Document>(docOrId: HydratedDocType | Types.ObjectId, MongooseModel: Model<any, any, any, any, HydratedDocType>, err?: Error | (() => Error)) => Promise<HydratedDocType>;
198
+ declare const findOrReturnInstance: <HydratedDocType extends Document>(docOrId: HydratedDocType | Types.ObjectId | string, MongooseModel: Model<any, any, any, any, HydratedDocType>, err?: Error | (() => Error)) => Promise<HydratedDocType>;
198
199
  /**
199
200
  * Finds multiple Mongoose documents by their IDs or returns the provided instances.
200
201
  *
@@ -206,13 +207,65 @@ declare const findOrReturnInstance: <HydratedDocType extends Document>(docOrId:
206
207
  * that are not already represented by instances.
207
208
  *
208
209
  * @template HydratedDocType - The type of the hydrated documents, extending `Document`.
209
- * @param {(HydratedDocType | Types.ObjectId)[]} docOrIds
210
- * - An array of document instances or ObjectIds to find.
210
+ * @param {(HydratedDocType | Types.ObjectId | string)[]} docOrIds
211
+ * - An array of document instances, ObjectIds, or string IDs to find.
211
212
  * @param {Model<any, any, any, any, HydratedDocType>} MongooseModel
212
213
  * - The Mongoose model used to query the database.
213
214
  * @returns {Promise<HydratedDocType[]>}
214
215
  * A promise that resolves to an array of hydrated document instances.
215
216
  */
216
- declare const findOrReturnManyInstances: <HydratedDocType extends Document>(docOrIds: (HydratedDocType | Types.ObjectId)[], MongooseModel: Model<any, any, any, any, HydratedDocType>) => Promise<HydratedDocType[]>;
217
+ declare const findOrReturnManyInstances: <HydratedDocType extends Document>(docOrIds: (HydratedDocType | Types.ObjectId | string)[], MongooseModel: Model<any, any, any, any, HydratedDocType>) => Promise<HydratedDocType[]>;
218
+ /**
219
+ * Type guard that checks if a potentially populated Mongoose field
220
+ * is actually a populated document rather than an ObjectId.
221
+ *
222
+ * This is useful for narrowing the type of a `PopulatedDoc<HydratedDocType>`
223
+ * field after conditionally populating a query.
224
+ *
225
+ * @template HydratedDocType - The type of the populated document, extending `Document`.
226
+ * @param {PopulatedDoc<HydratedDocType>} value
227
+ * - The value to check, which may be either a populated document or an ObjectId.
228
+ * @returns {value is HydratedDocType} `true` if the value is a populated document.
229
+ */
230
+ declare const isPopulated: <HydratedDocType extends Document>(value: PopulatedDoc<HydratedDocType>) => value is HydratedDocType;
231
+ /**
232
+ * Converts a string, ObjectId, or Document to a `Types.ObjectId`.
233
+ *
234
+ * If the value is already an `ObjectId`, it is returned as-is.
235
+ * If the value is a Document, its `_id` is returned.
236
+ * If the value is a string, a new `Types.ObjectId` is constructed from it.
237
+ *
238
+ * @param {string | Types.ObjectId | Document} value - The value to convert.
239
+ * @returns {Types.ObjectId} The resulting ObjectId.
240
+ * @throws {Error} If the string is not a valid 24-character hex string.
241
+ */
242
+ declare const toObjectId: (value: string | Types.ObjectId | Document) => Types.ObjectId;
243
+ /**
244
+ * Compares two values by their underlying MongoDB document ID.
245
+ *
246
+ * Each value can be a string, `ObjectId`, `Document`, or `PopulatedDoc`.
247
+ * Returns `false` if either value is `null` or `undefined`.
248
+ *
249
+ * @param {string | Types.ObjectId | Document | PopulatedDoc<any> | null | undefined} a
250
+ * - The first value to compare.
251
+ * @param {string | Types.ObjectId | Document | PopulatedDoc<any> | null | undefined} b
252
+ * - The second value to compare.
253
+ * @returns {boolean} `true` if both values resolve to the same ID string.
254
+ */
255
+ declare const areIdsEqual: (a: string | Types.ObjectId | Document | PopulatedDoc<any> | null | undefined, b: string | Types.ObjectId | Document | PopulatedDoc<any> | null | undefined) => boolean;
256
+ /**
257
+ * Asserts that a potentially populated Mongoose field is actually a populated document.
258
+ *
259
+ * This is the assertion counterpart of `isPopulated`. If the value is not populated,
260
+ * an error is thrown. Otherwise, the value is returned with its type narrowed to
261
+ * `HydratedDocType`.
262
+ *
263
+ * @template HydratedDocType - The type of the populated document, extending `Document`.
264
+ * @param {PopulatedDoc<HydratedDocType>} value
265
+ * - The value to check, which may be either a populated document or an ObjectId.
266
+ * @returns {HydratedDocType} The populated document.
267
+ * @throws {Error} If the value is not a populated document.
268
+ */
269
+ declare const ensurePopulated: <HydratedDocType extends Document>(value: PopulatedDoc<HydratedDocType>) => HydratedDocType;
217
270
 
218
- export { type ToMapQueryHelpers, type ToRecordsQueryHelpers, findOrReturnInstance, findOrReturnManyInstances, getPopulatedDocumentId, toMapPlugin as toMap, toRecordsPlugin as toRecords };
271
+ export { type ToMapQueryHelpers, type ToRecordsQueryHelpers, areIdsEqual, ensurePopulated, findOrReturnInstance, findOrReturnManyInstances, getPopulatedDocumentId, isPopulated, toMapPlugin as toMap, toObjectId, toRecordsPlugin as toRecords };
package/dist/index.js CHANGED
@@ -42,11 +42,11 @@ var getPopulatedDocumentId = (populatedDocument) => {
42
42
  if (populatedDocument instanceof Types.ObjectId) {
43
43
  return populatedDocument.toString();
44
44
  }
45
- const id = populatedDocument?.id || populatedDocument?._id;
46
- if (id) {
47
- return id.toString();
45
+ const _id = populatedDocument?._id;
46
+ if (_id) {
47
+ return _id.toString();
48
48
  }
49
- throw new Error("document incorrect");
49
+ throw new Error(`Expected a populated document or ObjectId, got: ${typeof populatedDocument}`);
50
50
  };
51
51
  var findOrReturnInstance = async (docOrId, MongooseModel, err) => {
52
52
  if (docOrId instanceof MongooseModel) {
@@ -61,6 +61,8 @@ var findOrReturnManyInstances = async (docOrIds, MongooseModel) => {
61
61
  acc[0].push(docOrId);
62
62
  } else if (docOrId instanceof Types.ObjectId) {
63
63
  acc[1].push(docOrId);
64
+ } else if (typeof docOrId === "string") {
65
+ acc[1].push(new Types.ObjectId(docOrId));
64
66
  }
65
67
  return acc;
66
68
  }, [[], []]);
@@ -74,10 +76,56 @@ var findOrReturnManyInstances = async (docOrIds, MongooseModel) => {
74
76
  }
75
77
  return result;
76
78
  };
79
+ var isPopulated = (value) => {
80
+ if (value instanceof Types.ObjectId) {
81
+ return false;
82
+ }
83
+ if (value != null && typeof value === "object" && ("_id" in value || "id" in value)) {
84
+ return true;
85
+ }
86
+ return false;
87
+ };
88
+ var toObjectId = (value) => {
89
+ if (value instanceof Types.ObjectId) {
90
+ return value;
91
+ }
92
+ if (typeof value === "object" && value !== null && "_id" in value) {
93
+ return value._id;
94
+ }
95
+ return new Types.ObjectId(value);
96
+ };
97
+ var areIdsEqual = (a, b) => {
98
+ if (a == null || b == null) {
99
+ return false;
100
+ }
101
+ const normalize = (val) => {
102
+ if (typeof val === "string") {
103
+ return val;
104
+ }
105
+ if (val instanceof Types.ObjectId) {
106
+ return val.toString();
107
+ }
108
+ if (typeof val === "object" && "_id" in val) {
109
+ return val._id.toString();
110
+ }
111
+ return String(val);
112
+ };
113
+ return normalize(a) === normalize(b);
114
+ };
115
+ var ensurePopulated = (value) => {
116
+ if (isPopulated(value)) {
117
+ return value;
118
+ }
119
+ throw new Error(`Expected a populated document, got: ${typeof value}`);
120
+ };
77
121
  export {
122
+ areIdsEqual,
123
+ ensurePopulated,
78
124
  findOrReturnInstance,
79
125
  findOrReturnManyInstances,
80
126
  getPopulatedDocumentId,
127
+ isPopulated,
81
128
  toMap_default as toMap,
129
+ toObjectId,
82
130
  toRecords_default as toRecords
83
131
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mongoose-utility-kit",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "A set of utility functions for the Mongoose library",
5
5
  "keywords": [
6
6
  "mongoose",
@@ -14,6 +14,9 @@
14
14
  "repository": "git@github.com:nikzanda/mongoose-utility-kit.git",
15
15
  "author": "Nicolò Zandarin <nikzanda@hotmail.it>",
16
16
  "license": "MIT",
17
+ "engines": {
18
+ "node": ">=18"
19
+ },
17
20
  "exports": {
18
21
  "./package.json": "./package.json",
19
22
  ".": {
@@ -41,7 +44,7 @@
41
44
  "eslint-plugin-import": "^2.31.0",
42
45
  "jest": "^29.7.0",
43
46
  "mongodb-memory-server": "^10.1.4",
44
- "mongoose": ">=8",
47
+ "mongoose": "8",
45
48
  "mongoose-lean-virtuals": "^2.0.0",
46
49
  "ts-jest": "^29.2.5",
47
50
  "tsup": "^8.3.6",
@@ -7,7 +7,7 @@ import { ExtractRawDocType, ExtractVirtualsType } from '../types';
7
7
  *
8
8
  * @template T The type of the `HydratedDocument`.
9
9
  */
10
- export interface ToMapQueryHelpers<RawDocType, HydratedDocType, TVirtuals> {
10
+ export interface ToMapQueryHelpers<RawDocType, HydratedDocType, TVirtuals = {}> {
11
11
  /**
12
12
  * Query helper interface for converting query results into a `Map` keyed by string,
13
13
  * including virtual properties.
@@ -6,7 +6,7 @@ import { ExtractRawDocType, ExtractVirtualsType } from '../types';
6
6
  *
7
7
  * @template T The type of the `HydratedDocument`.
8
8
  */
9
- export interface ToRecordsQueryHelpers<RawDocType, HydratedDocType, TVirtuals> {
9
+ export interface ToRecordsQueryHelpers<RawDocType, HydratedDocType, TVirtuals = {}> {
10
10
  /**
11
11
  * Query helper for transforming query results into a `Record<string, T>` object,
12
12
  * including virtual properties.
@@ -26,12 +26,12 @@ export const getPopulatedDocumentId = <HydratedDocType extends Document>(
26
26
  return populatedDocument.toString();
27
27
  }
28
28
 
29
- const id = populatedDocument?.id || populatedDocument?._id;
30
- if (id) {
31
- return id.toString();
29
+ const _id = populatedDocument?._id;
30
+ if (_id) {
31
+ return _id.toString();
32
32
  }
33
33
 
34
- throw new Error('document incorrect');
34
+ throw new Error(`Expected a populated document or ObjectId, got: ${typeof populatedDocument}`);
35
35
  };
36
36
 
37
37
  /**
@@ -44,7 +44,8 @@ export const getPopulatedDocumentId = <HydratedDocType extends Document>(
44
44
  * through the `err` parameter.
45
45
  *
46
46
  * @template HydratedDocType - The type of the hydrated document, extending `Document`.
47
- * @param {HydratedDocType | Types.ObjectId} docOrId - The document instance or ObjectId to find.
47
+ * @param {HydratedDocType | Types.ObjectId | string} docOrId
48
+ * - The document instance, ObjectId, or string ID to find.
48
49
  * @param {Model<any, any, any, any, HydratedDocType>} MongooseModel
49
50
  * - The Mongoose model used to query the database.
50
51
  * @param {Error | (() => Error)} [err]
@@ -53,7 +54,7 @@ export const getPopulatedDocumentId = <HydratedDocType extends Document>(
53
54
  * @throws {Error} - Throws an error if the document is not found and no custom error is provided.
54
55
  */
55
56
  export const findOrReturnInstance = async <HydratedDocType extends Document>(
56
- docOrId: HydratedDocType | Types.ObjectId,
57
+ docOrId: HydratedDocType | Types.ObjectId | string,
57
58
  MongooseModel: Model<any, any, any, any, HydratedDocType>,
58
59
  err?: Error | (() => Error),
59
60
  ): Promise<HydratedDocType> => {
@@ -78,15 +79,15 @@ export const findOrReturnInstance = async <HydratedDocType extends Document>(
78
79
  * that are not already represented by instances.
79
80
  *
80
81
  * @template HydratedDocType - The type of the hydrated documents, extending `Document`.
81
- * @param {(HydratedDocType | Types.ObjectId)[]} docOrIds
82
- * - An array of document instances or ObjectIds to find.
82
+ * @param {(HydratedDocType | Types.ObjectId | string)[]} docOrIds
83
+ * - An array of document instances, ObjectIds, or string IDs to find.
83
84
  * @param {Model<any, any, any, any, HydratedDocType>} MongooseModel
84
85
  * - The Mongoose model used to query the database.
85
86
  * @returns {Promise<HydratedDocType[]>}
86
87
  * A promise that resolves to an array of hydrated document instances.
87
88
  */
88
89
  export const findOrReturnManyInstances = async <HydratedDocType extends Document>(
89
- docOrIds: (HydratedDocType | Types.ObjectId)[],
90
+ docOrIds: (HydratedDocType | Types.ObjectId | string)[],
90
91
  MongooseModel: Model<any, any, any, any, HydratedDocType>,
91
92
  ): Promise<HydratedDocType[]> => {
92
93
  const [result, objectIds] = docOrIds
@@ -97,6 +98,9 @@ export const findOrReturnManyInstances = async <HydratedDocType extends Document
97
98
  else if (docOrId instanceof Types.ObjectId) {
98
99
  acc[1].push(docOrId);
99
100
  }
101
+ else if (typeof docOrId === 'string') {
102
+ acc[1].push(new Types.ObjectId(docOrId));
103
+ }
100
104
  return acc;
101
105
  }, [[], []]);
102
106
  if (objectIds.length > 0) {
@@ -109,3 +113,110 @@ export const findOrReturnManyInstances = async <HydratedDocType extends Document
109
113
  }
110
114
  return result;
111
115
  };
116
+
117
+ /**
118
+ * Type guard that checks if a potentially populated Mongoose field
119
+ * is actually a populated document rather than an ObjectId.
120
+ *
121
+ * This is useful for narrowing the type of a `PopulatedDoc<HydratedDocType>`
122
+ * field after conditionally populating a query.
123
+ *
124
+ * @template HydratedDocType - The type of the populated document, extending `Document`.
125
+ * @param {PopulatedDoc<HydratedDocType>} value
126
+ * - The value to check, which may be either a populated document or an ObjectId.
127
+ * @returns {value is HydratedDocType} `true` if the value is a populated document.
128
+ */
129
+ export const isPopulated = <HydratedDocType extends Document>(
130
+ value: PopulatedDoc<HydratedDocType>,
131
+ ): value is HydratedDocType => {
132
+ if (value instanceof Types.ObjectId) {
133
+ return false;
134
+ }
135
+ if (value != null && typeof value === 'object' && ('_id' in value || 'id' in value)) {
136
+ return true;
137
+ }
138
+ return false;
139
+ };
140
+
141
+ /**
142
+ * Converts a string, ObjectId, or Document to a `Types.ObjectId`.
143
+ *
144
+ * If the value is already an `ObjectId`, it is returned as-is.
145
+ * If the value is a Document, its `_id` is returned.
146
+ * If the value is a string, a new `Types.ObjectId` is constructed from it.
147
+ *
148
+ * @param {string | Types.ObjectId | Document} value - The value to convert.
149
+ * @returns {Types.ObjectId} The resulting ObjectId.
150
+ * @throws {Error} If the string is not a valid 24-character hex string.
151
+ */
152
+ export const toObjectId = (
153
+ value: string | Types.ObjectId | Document,
154
+ ): Types.ObjectId => {
155
+ if (value instanceof Types.ObjectId) {
156
+ return value;
157
+ }
158
+ if (typeof value === 'object' && value !== null && '_id' in value) {
159
+ return value._id;
160
+ }
161
+ return new Types.ObjectId(value as string);
162
+ };
163
+
164
+ /**
165
+ * Compares two values by their underlying MongoDB document ID.
166
+ *
167
+ * Each value can be a string, `ObjectId`, `Document`, or `PopulatedDoc`.
168
+ * Returns `false` if either value is `null` or `undefined`.
169
+ *
170
+ * @param {string | Types.ObjectId | Document | PopulatedDoc<any> | null | undefined} a
171
+ * - The first value to compare.
172
+ * @param {string | Types.ObjectId | Document | PopulatedDoc<any> | null | undefined} b
173
+ * - The second value to compare.
174
+ * @returns {boolean} `true` if both values resolve to the same ID string.
175
+ */
176
+ export const areIdsEqual = (
177
+ a: string | Types.ObjectId | Document | PopulatedDoc<any> | null | undefined,
178
+ b: string | Types.ObjectId | Document | PopulatedDoc<any> | null | undefined,
179
+ ): boolean => {
180
+ if (a == null || b == null) {
181
+ return false;
182
+ }
183
+
184
+ const normalize = (
185
+ val: string | Types.ObjectId | Document | PopulatedDoc<any>,
186
+ ): string => {
187
+ if (typeof val === 'string') {
188
+ return val;
189
+ }
190
+ if (val instanceof Types.ObjectId) {
191
+ return val.toString();
192
+ }
193
+ if (typeof val === 'object' && '_id' in val) {
194
+ return val._id.toString();
195
+ }
196
+ return String(val);
197
+ };
198
+
199
+ return normalize(a) === normalize(b);
200
+ };
201
+
202
+ /**
203
+ * Asserts that a potentially populated Mongoose field is actually a populated document.
204
+ *
205
+ * This is the assertion counterpart of `isPopulated`. If the value is not populated,
206
+ * an error is thrown. Otherwise, the value is returned with its type narrowed to
207
+ * `HydratedDocType`.
208
+ *
209
+ * @template HydratedDocType - The type of the populated document, extending `Document`.
210
+ * @param {PopulatedDoc<HydratedDocType>} value
211
+ * - The value to check, which may be either a populated document or an ObjectId.
212
+ * @returns {HydratedDocType} The populated document.
213
+ * @throws {Error} If the value is not a populated document.
214
+ */
215
+ export const ensurePopulated = <HydratedDocType extends Document>(
216
+ value: PopulatedDoc<HydratedDocType>,
217
+ ): HydratedDocType => {
218
+ if (isPopulated(value)) {
219
+ return value;
220
+ }
221
+ throw new Error(`Expected a populated document, got: ${typeof value}`);
222
+ };
@@ -1,8 +1,6 @@
1
1
  import {
2
2
  HydratedSingleSubdocument,
3
- Model,
4
3
  Schema,
5
- SchemaOptions,
6
4
  SchemaTypes,
7
5
  } from 'mongoose';
8
6
 
@@ -16,13 +14,7 @@ export interface IAddress {
16
14
 
17
15
  export type AddressInstance = HydratedSingleSubdocument<IAddress>;
18
16
 
19
- type AddressModelType = Model<IAddress, {}, {}, {}, AddressInstance>;
20
-
21
- const options: SchemaOptions<IAddress> = {
22
- _id: false,
23
- };
24
-
25
- const addressSchema = new Schema<IAddress, AddressModelType>({
17
+ const addressSchema = new Schema<IAddress>({
26
18
  streetAddress: {
27
19
  type: SchemaTypes.String,
28
20
  trim: true,
@@ -43,6 +35,6 @@ const addressSchema = new Schema<IAddress, AddressModelType>({
43
35
  type: SchemaTypes.String,
44
36
  trim: true,
45
37
  },
46
- }, options);
38
+ }, { _id: false });
47
39
 
48
40
  export default addressSchema;
@@ -58,6 +58,11 @@ const userSchema = new Schema<IUser, UserModelType>({
58
58
  required: true,
59
59
  trim: true,
60
60
  },
61
+ surname: {
62
+ type: SchemaTypes.String,
63
+ required: true,
64
+ trim: true,
65
+ },
61
66
  email: {
62
67
  type: SchemaTypes.String,
63
68
  required: true,
@@ -1,9 +1,18 @@
1
1
  import { Types } from 'mongoose';
2
- import { findOrReturnInstance, getPopulatedDocumentId } from '../src';
2
+ import {
3
+ areIdsEqual,
4
+ ensurePopulated,
5
+ findOrReturnInstance,
6
+ findOrReturnManyInstances,
7
+ getPopulatedDocumentId,
8
+ isPopulated,
9
+ toObjectId,
10
+ } from '../src';
3
11
  import User, { UserHydratedDocument } from './initializers/models/user';
4
12
  import Comment, { IComment } from './initializers/models/comment';
5
13
 
6
14
  let user: UserHydratedDocument;
15
+ let user2: UserHydratedDocument;
7
16
 
8
17
  beforeAll(async () => {
9
18
  user = await User.create({
@@ -20,6 +29,20 @@ beforeAll(async () => {
20
29
  },
21
30
  });
22
31
 
32
+ user2 = await User.create({
33
+ name: 'Mario',
34
+ surname: 'Rossi',
35
+ email: 'mario.rossi@email.com',
36
+ password: 'password2',
37
+ address: {
38
+ streetAddress: '',
39
+ postalCode: '',
40
+ city: '',
41
+ province: '',
42
+ country: 'Italy',
43
+ },
44
+ });
45
+
23
46
  await Comment.create({
24
47
  user,
25
48
  text: 'post comment',
@@ -57,8 +80,8 @@ describe('getPopulatedDocumentId', () => {
57
80
  });
58
81
 
59
82
  it('should handle null or undefined input gracefully', () => {
60
- expect(() => getPopulatedDocumentId(null as any)).toThrow('document incorrect');
61
- expect(() => getPopulatedDocumentId(undefined as any)).toThrow('document incorrect');
83
+ expect(() => getPopulatedDocumentId(null as any)).toThrow('Expected a populated document or ObjectId, got: object');
84
+ expect(() => getPopulatedDocumentId(undefined as any)).toThrow('Expected a populated document or ObjectId, got: undefined');
62
85
  });
63
86
  });
64
87
 
@@ -89,7 +112,230 @@ describe('findOrReturnInstance', () => {
89
112
  });
90
113
 
91
114
  it('should throw an error if the document is not found', async () => {
92
- const invalidId = new Types.ObjectId(); // Generate an invalid ID
115
+ const invalidId = new Types.ObjectId();
93
116
  await expect(findOrReturnInstance(invalidId, Comment)).rejects.toThrow();
94
117
  });
118
+
119
+ it('should throw a custom Error instance when document is not found', async () => {
120
+ const invalidId = new Types.ObjectId();
121
+ const customError = new Error('Custom not found error');
122
+ await expect(
123
+ findOrReturnInstance(invalidId, Comment, customError),
124
+ ).rejects.toThrow('Custom not found error');
125
+ });
126
+
127
+ it('should throw an error from factory function when document is not found', async () => {
128
+ const invalidId = new Types.ObjectId();
129
+ const errorFactory = () => new Error('Factory error message');
130
+ await expect(
131
+ findOrReturnInstance(invalidId, Comment, errorFactory),
132
+ ).rejects.toThrow('Factory error message');
133
+ });
134
+
135
+ it('should find a document by string ID', async () => {
136
+ const result = await findOrReturnInstance(user._id.toString(), User);
137
+ expect(result.id).toBe(user.id);
138
+ expect(result.name).toBe(user.name);
139
+ expect(checkType(result)).toBe(true);
140
+ });
141
+ });
142
+
143
+ describe('findOrReturnManyInstances', () => {
144
+ it('should return documents from mixed instances and ObjectIds', async () => {
145
+ const result = await findOrReturnManyInstances(
146
+ [user, user2._id],
147
+ User,
148
+ );
149
+ expect(result).toHaveLength(2);
150
+ const ids = result.map((u) => u.id);
151
+ expect(ids).toContain(user.id);
152
+ expect(ids).toContain(user2.id);
153
+ result.forEach((u) => {
154
+ expect(checkType(u)).toBe(true);
155
+ });
156
+ });
157
+
158
+ it('should return instances directly when all are already documents', async () => {
159
+ const result = await findOrReturnManyInstances([user, user2], User);
160
+ expect(result).toHaveLength(2);
161
+ const ids = result.map((u) => u.id);
162
+ expect(ids).toContain(user.id);
163
+ expect(ids).toContain(user2.id);
164
+ });
165
+
166
+ it('should find documents when all are ObjectIds', async () => {
167
+ const result = await findOrReturnManyInstances(
168
+ [user._id, user2._id],
169
+ User,
170
+ );
171
+ expect(result).toHaveLength(2);
172
+ const ids = result.map((u) => u.id);
173
+ expect(ids).toContain(user.id);
174
+ expect(ids).toContain(user2.id);
175
+ });
176
+
177
+ it('should return an empty array for empty input', async () => {
178
+ const result = await findOrReturnManyInstances([], User);
179
+ expect(result).toHaveLength(0);
180
+ });
181
+
182
+ it('should silently ignore non-existent ObjectIds', async () => {
183
+ const nonExistentId = new Types.ObjectId();
184
+ const result = await findOrReturnManyInstances(
185
+ [user, nonExistentId],
186
+ User,
187
+ );
188
+ expect(result).toHaveLength(1);
189
+ expect(result[0].id).toBe(user.id);
190
+ });
191
+
192
+ it('should handle string IDs in the input array', async () => {
193
+ const result = await findOrReturnManyInstances(
194
+ [user, user2._id.toString()],
195
+ User,
196
+ );
197
+ expect(result).toHaveLength(2);
198
+ const ids = result.map((u) => u.id);
199
+ expect(ids).toContain(user.id);
200
+ expect(ids).toContain(user2.id);
201
+ });
202
+
203
+ it('should find documents when all are string IDs', async () => {
204
+ const result = await findOrReturnManyInstances(
205
+ [user._id.toString(), user2._id.toString()],
206
+ User,
207
+ );
208
+ expect(result).toHaveLength(2);
209
+ const ids = result.map((u) => u.id);
210
+ expect(ids).toContain(user.id);
211
+ expect(ids).toContain(user2.id);
212
+ });
213
+ });
214
+
215
+ describe('isPopulated', () => {
216
+ it('should return false for an ObjectId', async () => {
217
+ const comment = await Comment
218
+ .findOne()
219
+ .orFail();
220
+ expect(isPopulated(comment.user)).toBe(false);
221
+ });
222
+
223
+ it('should return true for a populated document', async () => {
224
+ const comment = await Comment
225
+ .findOne()
226
+ .populate<{ user: UserHydratedDocument }>('user')
227
+ .orFail();
228
+ expect(isPopulated(comment.user)).toBe(true);
229
+ });
230
+
231
+ it('should return false for null', () => {
232
+ expect(isPopulated(null as any)).toBe(false);
233
+ });
234
+
235
+ it('should return false for undefined', () => {
236
+ expect(isPopulated(undefined as any)).toBe(false);
237
+ });
238
+
239
+ it('should return true for a plain object with _id', () => {
240
+ const plainObj = { _id: new Types.ObjectId(), name: 'test' };
241
+ expect(isPopulated(plainObj as any)).toBe(true);
242
+ });
243
+ });
244
+
245
+ describe('toObjectId', () => {
246
+ it('should return the same ObjectId when given an ObjectId', () => {
247
+ const objectId = new Types.ObjectId();
248
+ const result = toObjectId(objectId);
249
+ expect(result).toBe(objectId);
250
+ });
251
+
252
+ it('should create an ObjectId from a valid hex string', () => {
253
+ const hex = new Types.ObjectId().toString();
254
+ const result = toObjectId(hex);
255
+ expect(result).toBeInstanceOf(Types.ObjectId);
256
+ expect(result.toString()).toBe(hex);
257
+ });
258
+
259
+ it('should return _id from a Document', () => {
260
+ const result = toObjectId(user);
261
+ expect(result).toBeInstanceOf(Types.ObjectId);
262
+ expect(result.toString()).toBe(user._id.toString());
263
+ });
264
+
265
+ it('should throw for an invalid hex string', () => {
266
+ expect(() => toObjectId('not-a-valid-objectid')).toThrow();
267
+ });
268
+ });
269
+
270
+ describe('areIdsEqual', () => {
271
+ it('should return true for the same ObjectId', () => {
272
+ expect(areIdsEqual(user._id, user._id)).toBe(true);
273
+ });
274
+
275
+ it('should return true for an ObjectId and its string representation', () => {
276
+ expect(areIdsEqual(user._id, user._id.toString())).toBe(true);
277
+ });
278
+
279
+ it('should return true for a Document and its ObjectId', () => {
280
+ expect(areIdsEqual(user, user._id)).toBe(true);
281
+ });
282
+
283
+ it('should return true for two Documents with the same _id', () => {
284
+ expect(areIdsEqual(user, user)).toBe(true);
285
+ });
286
+
287
+ it('should return false for different IDs', () => {
288
+ expect(areIdsEqual(user._id, user2._id)).toBe(false);
289
+ });
290
+
291
+ it('should return false when first argument is null', () => {
292
+ expect(areIdsEqual(null, user._id)).toBe(false);
293
+ });
294
+
295
+ it('should return false when second argument is null', () => {
296
+ expect(areIdsEqual(user._id, null)).toBe(false);
297
+ });
298
+
299
+ it('should return false when first argument is undefined', () => {
300
+ expect(areIdsEqual(undefined, user._id)).toBe(false);
301
+ });
302
+
303
+ it('should return false when both arguments are null', () => {
304
+ expect(areIdsEqual(null, null)).toBe(false);
305
+ });
306
+
307
+ it('should return true for a populated document and an ObjectId', async () => {
308
+ const comment = await Comment
309
+ .findOne()
310
+ .populate<{ user: UserHydratedDocument }>('user')
311
+ .orFail();
312
+ expect(areIdsEqual(comment.user, user._id)).toBe(true);
313
+ });
314
+ });
315
+
316
+ describe('ensurePopulated', () => {
317
+ it('should return the populated document', async () => {
318
+ const comment = await Comment
319
+ .findOne()
320
+ .populate<{ user: UserHydratedDocument }>('user')
321
+ .orFail();
322
+ const result = ensurePopulated(comment.user);
323
+ expect(result.name).toBe(user.name);
324
+ expect(checkType(result)).toBe(true);
325
+ });
326
+
327
+ it('should throw when given an ObjectId', async () => {
328
+ const comment = await Comment
329
+ .findOne()
330
+ .orFail();
331
+ expect(() => ensurePopulated(comment.user)).toThrow('Expected a populated document, got: object');
332
+ });
333
+
334
+ it('should throw when given null', () => {
335
+ expect(() => ensurePopulated(null as any)).toThrow('Expected a populated document, got: object');
336
+ });
337
+
338
+ it('should throw when given undefined', () => {
339
+ expect(() => ensurePopulated(undefined as any)).toThrow('Expected a populated document, got: undefined');
340
+ });
95
341
  });