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.
- package/.github/workflows/ci.yml +16 -2
- package/CHANGELOG.md +12 -0
- package/README.md +203 -42
- package/dist/index.cjs +56 -4
- package/dist/index.d.cts +120 -11
- package/dist/index.d.ts +120 -11
- package/dist/index.js +52 -4
- package/package.json +6 -2
- package/src/plugins/toMap.ts +25 -3
- package/src/plugins/toRecords.ts +36 -3
- package/src/populated/functions.ts +120 -9
- package/src/types.ts +17 -1
- package/tests/initializers/models/embedded/address.ts +2 -10
- package/tests/initializers/models/user.ts +10 -3
- package/tests/plugins.test.ts +22 -1
- package/tests/populated.test.ts +250 -4
|
@@ -26,12 +26,12 @@ export const getPopulatedDocumentId = <HydratedDocType extends Document>(
|
|
|
26
26
|
return populatedDocument.toString();
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
-
const
|
|
30
|
-
if (
|
|
31
|
-
return
|
|
29
|
+
const _id = populatedDocument?._id;
|
|
30
|
+
if (_id) {
|
|
31
|
+
return _id.toString();
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
-
throw new Error(
|
|
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
|
|
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
|
|
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
|
+
};
|
package/src/types.ts
CHANGED
|
@@ -7,4 +7,20 @@ import { HydratedDocument } from 'mongoose';
|
|
|
7
7
|
* @template T The type of the `HydratedDocument`.
|
|
8
8
|
* @returns The type of the document if `T` is a `HydratedDocument`, otherwise `never`.
|
|
9
9
|
*/
|
|
10
|
-
export type
|
|
10
|
+
export type ExtractRawDocType<T> = T extends HydratedDocument<infer U> ? U : never;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Extracts the virtuals type from a Mongoose `HydratedDocument`.
|
|
14
|
+
* This utility type is useful for accessing the shape of virtual properties
|
|
15
|
+
* defined on Mongoose schemas.
|
|
16
|
+
*
|
|
17
|
+
* @template T The type of the `HydratedDocument`.
|
|
18
|
+
* @returns The type of the virtuals if `T` is a `HydratedDocument`, otherwise `never`.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```ts
|
|
22
|
+
* type Virtuals = ExtractVirtualsType<HydratedDocument<MyDoc, MyVirtuals>>;
|
|
23
|
+
* // Virtuals is inferred as MyVirtuals
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
export type ExtractVirtualsType<T> = T extends HydratedDocument<any, infer U> ? U : never;
|
|
@@ -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
|
-
|
|
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
|
-
},
|
|
38
|
+
}, { _id: false });
|
|
47
39
|
|
|
48
40
|
export default addressSchema;
|
|
@@ -7,6 +7,7 @@ import {
|
|
|
7
7
|
HydratedDocument,
|
|
8
8
|
model,
|
|
9
9
|
} from 'mongoose';
|
|
10
|
+
import mongooseLeanVirtuals from 'mongoose-lean-virtuals';
|
|
10
11
|
import addressSchema, { AddressInstance, IAddress } from './embedded/address';
|
|
11
12
|
import {
|
|
12
13
|
toMap,
|
|
@@ -30,7 +31,7 @@ interface IUserDocumentOverrides {
|
|
|
30
31
|
address: AddressInstance;
|
|
31
32
|
}
|
|
32
33
|
|
|
33
|
-
interface IUserVirtuals {
|
|
34
|
+
export interface IUserVirtuals {
|
|
34
35
|
id: string;
|
|
35
36
|
fullName: string;
|
|
36
37
|
}
|
|
@@ -39,8 +40,8 @@ export type UserHydratedDocument = HydratedDocument<IUser, IUserDocumentOverride
|
|
|
39
40
|
|
|
40
41
|
export type UserModelType = Model<
|
|
41
42
|
IUser,
|
|
42
|
-
ToMapQueryHelpers<IUser, UserHydratedDocument> &
|
|
43
|
-
ToRecordsQueryHelpers<IUser, UserHydratedDocument>,
|
|
43
|
+
ToMapQueryHelpers<IUser, UserHydratedDocument, IUserVirtuals> &
|
|
44
|
+
ToRecordsQueryHelpers<IUser, UserHydratedDocument, IUserVirtuals>,
|
|
44
45
|
IUserDocumentOverrides,
|
|
45
46
|
IUserVirtuals,
|
|
46
47
|
UserHydratedDocument
|
|
@@ -57,6 +58,11 @@ const userSchema = new Schema<IUser, UserModelType>({
|
|
|
57
58
|
required: true,
|
|
58
59
|
trim: true,
|
|
59
60
|
},
|
|
61
|
+
surname: {
|
|
62
|
+
type: SchemaTypes.String,
|
|
63
|
+
required: true,
|
|
64
|
+
trim: true,
|
|
65
|
+
},
|
|
60
66
|
email: {
|
|
61
67
|
type: SchemaTypes.String,
|
|
62
68
|
required: true,
|
|
@@ -80,6 +86,7 @@ userSchema.virtual('fullName')
|
|
|
80
86
|
return `${this.name} ${this.surname}`;
|
|
81
87
|
});
|
|
82
88
|
|
|
89
|
+
userSchema.plugin(mongooseLeanVirtuals);
|
|
83
90
|
userSchema.plugin(toMap);
|
|
84
91
|
userSchema.plugin(toRecords);
|
|
85
92
|
|
package/tests/plugins.test.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import User, { UserHydratedDocument } from './initializers/models/user';
|
|
1
|
+
import User, { IUser, IUserVirtuals, UserHydratedDocument } from './initializers/models/user';
|
|
2
2
|
|
|
3
3
|
let user: UserHydratedDocument;
|
|
4
4
|
|
|
@@ -38,6 +38,17 @@ describe('toMap', () => {
|
|
|
38
38
|
expect(users.get(user._id.toString())!).not.toBeInstanceOf(User);
|
|
39
39
|
});
|
|
40
40
|
|
|
41
|
+
it('should return a map with lean documents and virtuals', async () => {
|
|
42
|
+
const users = await User
|
|
43
|
+
.find()
|
|
44
|
+
.lean<(IUser & IUserVirtuals)[]>({ virtuals: true })
|
|
45
|
+
.toMap();
|
|
46
|
+
expect(users).toBeTruthy();
|
|
47
|
+
expect(users.has(user._id.toString())).toBe(true);
|
|
48
|
+
expect(users.get(user._id.toString())!.fullName).toBeTruthy();
|
|
49
|
+
expect(users.get(user._id.toString())!).not.toBeInstanceOf(User);
|
|
50
|
+
});
|
|
51
|
+
|
|
41
52
|
it('should return an empty map if no documents are found', async () => {
|
|
42
53
|
const users = await User
|
|
43
54
|
.find({ email: 'non-existent@email.com' })
|
|
@@ -65,6 +76,16 @@ describe('toRecords', () => {
|
|
|
65
76
|
expect(users[user._id.toString()]).not.toBeInstanceOf(User);
|
|
66
77
|
});
|
|
67
78
|
|
|
79
|
+
it('should return a map with lean documents and virtuals', async () => {
|
|
80
|
+
const users = await User
|
|
81
|
+
.find()
|
|
82
|
+
.lean<(IUser & IUserVirtuals)[]>({ virtuals: true })
|
|
83
|
+
.toRecords();
|
|
84
|
+
expect(users).toBeTruthy();
|
|
85
|
+
expect(users[user._id.toString()].fullName).toBeTruthy();
|
|
86
|
+
expect(users[user._id.toString()]).not.toBeInstanceOf(User);
|
|
87
|
+
});
|
|
88
|
+
|
|
68
89
|
it('should return an empty map if no documents are found', async () => {
|
|
69
90
|
const users = await User
|
|
70
91
|
.find({ email: 'non-existent@email.com' })
|
package/tests/populated.test.ts
CHANGED
|
@@ -1,9 +1,18 @@
|
|
|
1
1
|
import { Types } from 'mongoose';
|
|
2
|
-
import {
|
|
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
|
|
61
|
-
expect(() => getPopulatedDocumentId(undefined as any)).toThrow('document
|
|
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();
|
|
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
|
});
|