@opra/mongodb 0.33.13 → 1.0.0-alpha.2
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/cjs/adapter-utils/prepare-filter.js +20 -28
- package/cjs/adapter-utils/prepare-projection.js +40 -39
- package/cjs/index.js +1 -2
- package/cjs/mongo-adapter.js +66 -1
- package/cjs/mongo-collection-service.js +72 -313
- package/cjs/mongo-entity-service.js +329 -0
- package/cjs/{mongo-array-service.js → mongo-nested-service.js} +231 -225
- package/cjs/mongo-service.js +124 -183
- package/cjs/mongo-singleton-service.js +28 -124
- package/esm/adapter-utils/prepare-filter.js +20 -28
- package/esm/adapter-utils/prepare-projection.js +39 -38
- package/esm/index.js +1 -2
- package/esm/mongo-adapter.js +66 -1
- package/esm/mongo-collection-service.js +73 -313
- package/esm/mongo-entity-service.js +324 -0
- package/esm/mongo-nested-service.js +569 -0
- package/esm/mongo-service.js +125 -184
- package/esm/mongo-singleton-service.js +29 -125
- package/package.json +9 -8
- package/types/adapter-utils/prepare-filter.d.ts +2 -3
- package/types/adapter-utils/prepare-projection.d.ts +4 -13
- package/types/index.d.ts +1 -2
- package/types/mongo-adapter.d.ts +14 -1
- package/types/mongo-collection-service.d.ts +88 -251
- package/types/mongo-entity-service.d.ts +149 -0
- package/types/mongo-nested-service.d.ts +258 -0
- package/types/mongo-service.d.ts +208 -82
- package/types/mongo-singleton-service.d.ts +39 -148
- package/cjs/types.js +0 -2
- package/esm/mongo-array-service.js +0 -563
- package/esm/types.js +0 -1
- package/types/mongo-array-service.d.ts +0 -409
- package/types/types.d.ts +0 -3
|
@@ -0,0 +1,569 @@
|
|
|
1
|
+
import omit from 'lodash.omit';
|
|
2
|
+
import { ComplexType, NotAcceptableError, ResourceNotAvailableError } from '@opra/common';
|
|
3
|
+
import { MongoAdapter } from './mongo-adapter.js';
|
|
4
|
+
import { MongoService } from './mongo-service.js';
|
|
5
|
+
/**
|
|
6
|
+
* A class that provides methods to perform operations on an array field in a MongoDB collection.
|
|
7
|
+
* @class MongoNestedService
|
|
8
|
+
* @template T The type of the array item.
|
|
9
|
+
*/
|
|
10
|
+
export class MongoNestedService extends MongoService {
|
|
11
|
+
/**
|
|
12
|
+
* Constructs a new instance
|
|
13
|
+
*
|
|
14
|
+
* @param {Type | string} dataType - The data type of the array elements.
|
|
15
|
+
* @param {string} fieldName - The name of the field in the document representing the array.
|
|
16
|
+
* @param {MongoNestedService.Options} [options] - The options for the array service.
|
|
17
|
+
* @constructor
|
|
18
|
+
*/
|
|
19
|
+
constructor(dataType, fieldName, options) {
|
|
20
|
+
super(dataType, options);
|
|
21
|
+
this.fieldName = fieldName;
|
|
22
|
+
this.nestedKey = options?.nestedKey || '_id';
|
|
23
|
+
this.defaultLimit = options?.defaultLimit || 10;
|
|
24
|
+
this.$nestedFilter = options?.$nestedFilter;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Asserts whether a resource with the specified parentId and id exists.
|
|
28
|
+
* Throws a ResourceNotFoundError if the resource does not exist.
|
|
29
|
+
*
|
|
30
|
+
* @param {MongoAdapter.AnyId} documentId - The ID of the parent document.
|
|
31
|
+
* @param {MongoAdapter.AnyId} id - The ID of the resource.
|
|
32
|
+
* @param {MongoNestedService.ExistsOptions<T>} [options] - Optional parameters for checking resource existence.
|
|
33
|
+
* @return {Promise<void>} - A promise that resolves with no value upon success.
|
|
34
|
+
* @throws {ResourceNotAvailableError} - If the resource does not exist.
|
|
35
|
+
*/
|
|
36
|
+
async assert(documentId, id, options) {
|
|
37
|
+
if (!(await this.exists(documentId, id, options)))
|
|
38
|
+
throw new ResourceNotAvailableError(this.getResourceName() + '.' + this.nestedKey, documentId + '/' + id);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Adds a single item into the array field.
|
|
42
|
+
*
|
|
43
|
+
* @param {MongoAdapter.AnyId} documentId - The ID of the parent document.
|
|
44
|
+
* @param {T} input - The item to be added to the array field.
|
|
45
|
+
* @param {MongoNestedService.CreateOptions} [options] - Optional options for the create operation.
|
|
46
|
+
* @return {Promise<PartialDTO<T>>} - A promise that resolves with the partial output of the created item.
|
|
47
|
+
* @throws {ResourceNotAvailableError} - If the parent document is not found.
|
|
48
|
+
*/
|
|
49
|
+
async create(documentId, input, options) {
|
|
50
|
+
const id = input._id || this._generateId();
|
|
51
|
+
if (id != null)
|
|
52
|
+
input._id = id;
|
|
53
|
+
const info = {
|
|
54
|
+
crud: 'create',
|
|
55
|
+
method: 'create',
|
|
56
|
+
byId: false,
|
|
57
|
+
documentId,
|
|
58
|
+
nestedId: id,
|
|
59
|
+
input,
|
|
60
|
+
options,
|
|
61
|
+
};
|
|
62
|
+
return this._intercept(() => this._create(documentId, input, options), info);
|
|
63
|
+
}
|
|
64
|
+
async _create(documentId, input, options) {
|
|
65
|
+
const encode = this.getEncoder('create');
|
|
66
|
+
const doc = encode(input);
|
|
67
|
+
doc._id = doc._id || this._generateId();
|
|
68
|
+
const docFilter = MongoAdapter.prepareKeyValues(documentId, ['_id']);
|
|
69
|
+
const r = await this._dbUpdateOne(docFilter, {
|
|
70
|
+
$push: { [this.fieldName]: doc },
|
|
71
|
+
}, options);
|
|
72
|
+
if (r.matchedCount) {
|
|
73
|
+
if (!options)
|
|
74
|
+
return doc;
|
|
75
|
+
const id = doc[this.nestedKey];
|
|
76
|
+
const out = await this._findById(documentId, id, {
|
|
77
|
+
...options,
|
|
78
|
+
filter: undefined,
|
|
79
|
+
skip: undefined,
|
|
80
|
+
});
|
|
81
|
+
if (out)
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
throw new ResourceNotAvailableError(this.getResourceName(), documentId);
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Counts the number of documents in the collection that match the specified parentId and options.
|
|
88
|
+
*
|
|
89
|
+
* @param {MongoAdapter.AnyId} documentId - The ID of the parent document.
|
|
90
|
+
* @param {MongoNestedService.CountOptions<T>} [options] - Optional parameters for counting.
|
|
91
|
+
* @returns {Promise<number>} - A promise that resolves to the count of documents.
|
|
92
|
+
*/
|
|
93
|
+
async count(documentId, options) {
|
|
94
|
+
const info = {
|
|
95
|
+
crud: 'read',
|
|
96
|
+
method: 'count',
|
|
97
|
+
byId: false,
|
|
98
|
+
documentId,
|
|
99
|
+
options,
|
|
100
|
+
};
|
|
101
|
+
return this._intercept(async () => {
|
|
102
|
+
const documentFilter = MongoAdapter.prepareFilter([await this._getDocumentFilter(info)]);
|
|
103
|
+
const filter = MongoAdapter.prepareFilter([await this._getNestedFilter(info), options?.filter]);
|
|
104
|
+
return this._count(documentId, { ...options, filter, documentFilter });
|
|
105
|
+
}, info);
|
|
106
|
+
}
|
|
107
|
+
async _count(documentId, options) {
|
|
108
|
+
const matchFilter = MongoAdapter.prepareFilter([
|
|
109
|
+
MongoAdapter.prepareKeyValues(documentId, ['_id']),
|
|
110
|
+
options?.documentFilter,
|
|
111
|
+
]);
|
|
112
|
+
const stages = [
|
|
113
|
+
{ $match: matchFilter },
|
|
114
|
+
{ $unwind: { path: '$' + this.fieldName } },
|
|
115
|
+
{ $replaceRoot: { newRoot: '$' + this.fieldName } },
|
|
116
|
+
];
|
|
117
|
+
if (options?.filter) {
|
|
118
|
+
const filter = MongoAdapter.prepareFilter(options?.filter);
|
|
119
|
+
stages.push({ $match: filter });
|
|
120
|
+
}
|
|
121
|
+
stages.push({ $count: '*' });
|
|
122
|
+
const r = await this._dbAggregate(stages, options);
|
|
123
|
+
try {
|
|
124
|
+
const n = await r.next();
|
|
125
|
+
return n?.['*'] || 0;
|
|
126
|
+
}
|
|
127
|
+
finally {
|
|
128
|
+
await r.close();
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Deletes an element from an array within a document in the MongoDB collection.
|
|
133
|
+
*
|
|
134
|
+
* @param {MongoAdapter.AnyId} documentId - The ID of the parent document.
|
|
135
|
+
* @param {MongoAdapter.AnyId} nestedId - The ID of the element to delete from the nested array.
|
|
136
|
+
* @param {MongoNestedService.DeleteOptions<T>} [options] - Additional options for the delete operation.
|
|
137
|
+
* @return {Promise<number>} - A Promise that resolves to the number of elements deleted (1 if successful, 0 if not).
|
|
138
|
+
*/
|
|
139
|
+
async delete(documentId, nestedId, options) {
|
|
140
|
+
const info = {
|
|
141
|
+
crud: 'delete',
|
|
142
|
+
method: 'delete',
|
|
143
|
+
byId: true,
|
|
144
|
+
documentId,
|
|
145
|
+
nestedId,
|
|
146
|
+
options,
|
|
147
|
+
};
|
|
148
|
+
return this._intercept(async () => {
|
|
149
|
+
const documentFilter = MongoAdapter.prepareFilter([await this._getDocumentFilter(info)]);
|
|
150
|
+
const filter = MongoAdapter.prepareFilter([await this._getNestedFilter(info), options?.filter]);
|
|
151
|
+
return this._delete(documentId, nestedId, { ...options, filter, documentFilter });
|
|
152
|
+
}, info);
|
|
153
|
+
}
|
|
154
|
+
async _delete(documentId, nestedId, options) {
|
|
155
|
+
const matchFilter = MongoAdapter.prepareFilter([
|
|
156
|
+
MongoAdapter.prepareKeyValues(documentId, ['_id']),
|
|
157
|
+
options?.documentFilter,
|
|
158
|
+
]);
|
|
159
|
+
const pullFilter = MongoAdapter.prepareFilter([MongoAdapter.prepareKeyValues(nestedId, [this.nestedKey]), options?.filter]) || {};
|
|
160
|
+
const r = await this._dbUpdateOne(matchFilter, {
|
|
161
|
+
$pull: { [this.fieldName]: pullFilter },
|
|
162
|
+
}, options);
|
|
163
|
+
return r.modifiedCount ? 1 : 0;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Deletes multiple items from a collection based on the parent ID and optional filter.
|
|
167
|
+
*
|
|
168
|
+
* @param {MongoAdapter.AnyId} documentId - The ID of the parent document.
|
|
169
|
+
* @param {MongoNestedService.DeleteManyOptions<T>} [options] - Optional options to specify a filter.
|
|
170
|
+
* @returns {Promise<number>} - A Promise that resolves to the number of items deleted.
|
|
171
|
+
*/
|
|
172
|
+
async deleteMany(documentId, options) {
|
|
173
|
+
const info = {
|
|
174
|
+
crud: 'delete',
|
|
175
|
+
method: 'deleteMany',
|
|
176
|
+
byId: false,
|
|
177
|
+
documentId,
|
|
178
|
+
options,
|
|
179
|
+
};
|
|
180
|
+
return this._intercept(async () => {
|
|
181
|
+
const documentFilter = MongoAdapter.prepareFilter([await this._getDocumentFilter(info)]);
|
|
182
|
+
const filter = MongoAdapter.prepareFilter([await this._getNestedFilter(info), options?.filter]);
|
|
183
|
+
return this._deleteMany(documentId, { ...options, filter, documentFilter });
|
|
184
|
+
}, info);
|
|
185
|
+
}
|
|
186
|
+
async _deleteMany(documentId, options) {
|
|
187
|
+
const matchFilter = MongoAdapter.prepareFilter([
|
|
188
|
+
MongoAdapter.prepareKeyValues(documentId, ['_id']),
|
|
189
|
+
options?.documentFilter,
|
|
190
|
+
]);
|
|
191
|
+
// Count matching items, we will use this as result
|
|
192
|
+
const matchCount = await this.count(documentId, options);
|
|
193
|
+
const pullFilter = MongoAdapter.prepareFilter(options?.filter) || {};
|
|
194
|
+
const r = await this._dbUpdateOne(matchFilter, {
|
|
195
|
+
$pull: { [this.fieldName]: pullFilter },
|
|
196
|
+
}, options);
|
|
197
|
+
if (r.matchedCount)
|
|
198
|
+
return matchCount;
|
|
199
|
+
return 0;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Checks if an array element with the given parentId and id exists.
|
|
203
|
+
*
|
|
204
|
+
* @param {MongoAdapter.AnyId} documentId - The ID of the parent document.
|
|
205
|
+
* @param {MongoAdapter.AnyId} nestedId - The id of the record.
|
|
206
|
+
* @param {MongoNestedService.ExistsOptions<T>} [options] - The options for the exists method.
|
|
207
|
+
* @returns {Promise<boolean>} - A promise that resolves to a boolean indicating if the record exists or not.
|
|
208
|
+
*/
|
|
209
|
+
async exists(documentId, nestedId, options) {
|
|
210
|
+
return !!(await this.findById(documentId, nestedId, { ...options, projection: ['_id'] }));
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Checks if an object with the given arguments exists.
|
|
214
|
+
*
|
|
215
|
+
* @param {MongoAdapter.AnyId} documentId - The ID of the parent document.
|
|
216
|
+
* @param {MongoNestedService.ExistsOneOptions} [options] - The options for the query (optional).
|
|
217
|
+
* @return {Promise<boolean>} - A Promise that resolves to a boolean indicating whether the object exists or not.
|
|
218
|
+
*/
|
|
219
|
+
async existsOne(documentId, options) {
|
|
220
|
+
return !!(await this.findOne(documentId, { ...options, projection: ['_id'] }));
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Finds an element in array field by its parent ID and ID.
|
|
224
|
+
*
|
|
225
|
+
* @param {MongoAdapter.AnyId} documentId - The ID of the document.
|
|
226
|
+
* @param {MongoAdapter.AnyId} nestedId - The ID of the document.
|
|
227
|
+
* @param {MongoNestedService.FindOneOptions<T>} [options] - The optional options for the operation.
|
|
228
|
+
* @returns {Promise<PartialDTO<T> | undefined>} - A promise that resolves to the found document or undefined if not found.
|
|
229
|
+
*/
|
|
230
|
+
async findById(documentId, nestedId, options) {
|
|
231
|
+
const info = {
|
|
232
|
+
crud: 'read',
|
|
233
|
+
method: 'findById',
|
|
234
|
+
byId: true,
|
|
235
|
+
documentId,
|
|
236
|
+
nestedId,
|
|
237
|
+
options,
|
|
238
|
+
};
|
|
239
|
+
return this._intercept(async () => {
|
|
240
|
+
const documentFilter = MongoAdapter.prepareFilter([await this._getDocumentFilter(info)]);
|
|
241
|
+
const filter = MongoAdapter.prepareFilter([await this._getNestedFilter(info), options?.filter]);
|
|
242
|
+
return this._findById(documentId, nestedId, { ...options, filter, documentFilter });
|
|
243
|
+
}, info);
|
|
244
|
+
}
|
|
245
|
+
async _findById(documentId, nestedId, options) {
|
|
246
|
+
const filter = MongoAdapter.prepareFilter([
|
|
247
|
+
MongoAdapter.prepareKeyValues(nestedId, [this.nestedKey]),
|
|
248
|
+
options?.filter,
|
|
249
|
+
]);
|
|
250
|
+
const rows = await this._findMany(documentId, {
|
|
251
|
+
...options,
|
|
252
|
+
filter,
|
|
253
|
+
limit: 1,
|
|
254
|
+
skip: undefined,
|
|
255
|
+
sort: undefined,
|
|
256
|
+
});
|
|
257
|
+
return rows?.[0];
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Finds the first array element that matches the given parentId.
|
|
261
|
+
*
|
|
262
|
+
* @param {MongoAdapter.AnyId} documentId - The ID of the document.
|
|
263
|
+
* @param {MongoNestedService.FindOneOptions<T>} [options] - Optional options to customize the query.
|
|
264
|
+
* @returns {Promise<PartialDTO<T> | undefined>} A promise that resolves to the first matching document, or `undefined` if no match is found.
|
|
265
|
+
*/
|
|
266
|
+
async findOne(documentId, options) {
|
|
267
|
+
const info = {
|
|
268
|
+
crud: 'read',
|
|
269
|
+
method: 'findOne',
|
|
270
|
+
byId: false,
|
|
271
|
+
documentId,
|
|
272
|
+
options,
|
|
273
|
+
};
|
|
274
|
+
return this._intercept(async () => {
|
|
275
|
+
const documentFilter = MongoAdapter.prepareFilter([await this._getDocumentFilter(info)]);
|
|
276
|
+
const filter = MongoAdapter.prepareFilter([await this._getNestedFilter(info), options?.filter]);
|
|
277
|
+
return this._findOne(documentId, { ...options, filter, documentFilter });
|
|
278
|
+
}, info);
|
|
279
|
+
}
|
|
280
|
+
async _findOne(documentId, options) {
|
|
281
|
+
const rows = await this._findMany(documentId, {
|
|
282
|
+
...options,
|
|
283
|
+
limit: 1,
|
|
284
|
+
});
|
|
285
|
+
return rows?.[0];
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Finds multiple elements in an array field.
|
|
289
|
+
*
|
|
290
|
+
* @param {MongoAdapter.AnyId} documentId - The ID of the parent document.
|
|
291
|
+
* @param {MongoNestedService.FindManyOptions<T>} [options] - The options for finding the documents.
|
|
292
|
+
* @returns {Promise<PartialDTO<T>[]>} - The found documents.
|
|
293
|
+
*/
|
|
294
|
+
async findMany(documentId, options) {
|
|
295
|
+
const args = {
|
|
296
|
+
crud: 'read',
|
|
297
|
+
method: 'findMany',
|
|
298
|
+
byId: false,
|
|
299
|
+
documentId,
|
|
300
|
+
options,
|
|
301
|
+
};
|
|
302
|
+
return this._intercept(async () => {
|
|
303
|
+
const documentFilter = await this._getDocumentFilter(args);
|
|
304
|
+
const nestedFilter = await this._getNestedFilter(args);
|
|
305
|
+
return this._findMany(documentId, {
|
|
306
|
+
...options,
|
|
307
|
+
documentFilter,
|
|
308
|
+
nestedFilter,
|
|
309
|
+
limit: options?.limit || this.defaultLimit,
|
|
310
|
+
});
|
|
311
|
+
}, args);
|
|
312
|
+
}
|
|
313
|
+
async _findMany(documentId, options) {
|
|
314
|
+
const matchFilter = MongoAdapter.prepareFilter([
|
|
315
|
+
MongoAdapter.prepareKeyValues(documentId, ['_id']),
|
|
316
|
+
options.documentFilter,
|
|
317
|
+
]);
|
|
318
|
+
const mongoOptions = {
|
|
319
|
+
...omit(options, ['documentFilter', 'nestedFilter', 'projection', 'sort', 'skip', 'limit', 'filter', 'count']),
|
|
320
|
+
};
|
|
321
|
+
const limit = options?.limit || this.defaultLimit;
|
|
322
|
+
const stages = [
|
|
323
|
+
{ $match: matchFilter },
|
|
324
|
+
{ $unwind: { path: '$' + this.fieldName } },
|
|
325
|
+
{ $replaceRoot: { newRoot: '$' + this.fieldName } },
|
|
326
|
+
];
|
|
327
|
+
if (options?.filter || options.nestedFilter) {
|
|
328
|
+
const optionsFilter = MongoAdapter.prepareFilter([options?.filter, options.nestedFilter]);
|
|
329
|
+
stages.push({ $match: optionsFilter });
|
|
330
|
+
}
|
|
331
|
+
if (options?.skip)
|
|
332
|
+
stages.push({ $skip: options.skip });
|
|
333
|
+
if (options?.sort) {
|
|
334
|
+
const sort = MongoAdapter.prepareSort(options.sort);
|
|
335
|
+
if (sort)
|
|
336
|
+
stages.push({ $sort: sort });
|
|
337
|
+
}
|
|
338
|
+
stages.push({ $limit: limit });
|
|
339
|
+
const dataType = this.getDataType();
|
|
340
|
+
const projection = MongoAdapter.prepareProjection(dataType, options?.projection);
|
|
341
|
+
if (projection)
|
|
342
|
+
stages.push({ $project: projection });
|
|
343
|
+
const decode = this.getDecoder();
|
|
344
|
+
const cursor = await this._dbAggregate(stages, mongoOptions);
|
|
345
|
+
try {
|
|
346
|
+
const out = await (await cursor.toArray()).map((r) => decode(r));
|
|
347
|
+
return out;
|
|
348
|
+
}
|
|
349
|
+
finally {
|
|
350
|
+
if (!cursor.closed)
|
|
351
|
+
await cursor.close();
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Finds multiple elements in an array field.
|
|
356
|
+
*
|
|
357
|
+
* @param {MongoAdapter.AnyId} documentId - The ID of the parent document.
|
|
358
|
+
* @param {MongoNestedService.FindManyOptions<T>} [options] - The options for finding the documents.
|
|
359
|
+
* @returns {Promise<PartialDTO<T>[]>} - The found documents.
|
|
360
|
+
*/
|
|
361
|
+
async findManyWithCount(documentId, options) {
|
|
362
|
+
const args = {
|
|
363
|
+
crud: 'read',
|
|
364
|
+
method: 'findMany',
|
|
365
|
+
byId: false,
|
|
366
|
+
documentId,
|
|
367
|
+
options,
|
|
368
|
+
};
|
|
369
|
+
return this._intercept(async () => {
|
|
370
|
+
const documentFilter = await this._getDocumentFilter(args);
|
|
371
|
+
const nestedFilter = await this._getNestedFilter(args);
|
|
372
|
+
return this._findManyWithCount(documentId, {
|
|
373
|
+
...options,
|
|
374
|
+
documentFilter,
|
|
375
|
+
nestedFilter,
|
|
376
|
+
limit: options?.limit || this.defaultLimit,
|
|
377
|
+
});
|
|
378
|
+
}, args);
|
|
379
|
+
}
|
|
380
|
+
async _findManyWithCount(documentId, options) {
|
|
381
|
+
const matchFilter = MongoAdapter.prepareFilter([
|
|
382
|
+
MongoAdapter.prepareKeyValues(documentId, ['_id']),
|
|
383
|
+
options.documentFilter,
|
|
384
|
+
]);
|
|
385
|
+
const mongoOptions = {
|
|
386
|
+
...omit(options, ['pick', 'include', 'omit', 'sort', 'skip', 'limit', 'filter', 'count']),
|
|
387
|
+
};
|
|
388
|
+
const limit = options?.limit || this.defaultLimit;
|
|
389
|
+
const dataStages = [];
|
|
390
|
+
const stages = [
|
|
391
|
+
{ $match: matchFilter },
|
|
392
|
+
{ $unwind: { path: '$' + this.fieldName } },
|
|
393
|
+
{ $replaceRoot: { newRoot: '$' + this.fieldName } },
|
|
394
|
+
{
|
|
395
|
+
$facet: {
|
|
396
|
+
data: dataStages,
|
|
397
|
+
count: [{ $count: 'totalMatches' }],
|
|
398
|
+
},
|
|
399
|
+
},
|
|
400
|
+
];
|
|
401
|
+
if (options?.filter || options.nestedFilter) {
|
|
402
|
+
const optionsFilter = MongoAdapter.prepareFilter([options?.filter, options.nestedFilter]);
|
|
403
|
+
dataStages.push({ $match: optionsFilter });
|
|
404
|
+
}
|
|
405
|
+
if (options?.skip)
|
|
406
|
+
dataStages.push({ $skip: options.skip });
|
|
407
|
+
if (options?.sort) {
|
|
408
|
+
const sort = MongoAdapter.prepareSort(options.sort);
|
|
409
|
+
if (sort)
|
|
410
|
+
dataStages.push({ $sort: sort });
|
|
411
|
+
}
|
|
412
|
+
dataStages.push({ $limit: limit });
|
|
413
|
+
const dataType = this.getDataType();
|
|
414
|
+
const projection = MongoAdapter.prepareProjection(dataType, options?.projection);
|
|
415
|
+
if (projection)
|
|
416
|
+
dataStages.push({ $project: projection });
|
|
417
|
+
const decode = this.getDecoder();
|
|
418
|
+
const cursor = await this._dbAggregate(stages, {
|
|
419
|
+
...mongoOptions,
|
|
420
|
+
});
|
|
421
|
+
try {
|
|
422
|
+
const facetResult = await cursor.toArray();
|
|
423
|
+
return {
|
|
424
|
+
count: facetResult[0].count[0].totalMatches || 0,
|
|
425
|
+
items: facetResult[0].data.map((r) => decode(r)),
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
finally {
|
|
429
|
+
if (!cursor.closed)
|
|
430
|
+
await cursor.close();
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* Retrieves a specific item from the array of a document.
|
|
435
|
+
*
|
|
436
|
+
* @param {MongoAdapter.AnyId} documentId - The ID of the document.
|
|
437
|
+
* @param {MongoAdapter.AnyId} nestedId - The ID of the item.
|
|
438
|
+
* @param {MongoNestedService.FindOneOptions<T>} [options] - The options for finding the item.
|
|
439
|
+
* @returns {Promise<PartialDTO<T>>} - The item found.
|
|
440
|
+
* @throws {ResourceNotAvailableError} - If the item is not found.
|
|
441
|
+
*/
|
|
442
|
+
async get(documentId, nestedId, options) {
|
|
443
|
+
const out = await this.findById(documentId, nestedId, options);
|
|
444
|
+
if (!out)
|
|
445
|
+
throw new ResourceNotAvailableError(this.getResourceName() + '.' + this.nestedKey, documentId + '/' + nestedId);
|
|
446
|
+
return out;
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* Updates an array element with new data and returns the updated element
|
|
450
|
+
*
|
|
451
|
+
* @param {AnyId} documentId - The ID of the document to update.
|
|
452
|
+
* @param {AnyId} nestedId - The ID of the item to update within the document.
|
|
453
|
+
* @param {PatchDTO<T>} input - The new data to update the item with.
|
|
454
|
+
* @param {MongoNestedService.UpdateOptions<T>} [options] - Additional update options.
|
|
455
|
+
* @returns {Promise<PartialDTO<T> | undefined>} The updated item or undefined if it does not exist.
|
|
456
|
+
* @throws {Error} If an error occurs while updating the item.
|
|
457
|
+
*/
|
|
458
|
+
async update(documentId, nestedId, input, options) {
|
|
459
|
+
const r = await this.updateOnly(documentId, nestedId, input, options);
|
|
460
|
+
if (!r)
|
|
461
|
+
return;
|
|
462
|
+
const out = await this._findById(documentId, nestedId, {
|
|
463
|
+
...options,
|
|
464
|
+
sort: undefined,
|
|
465
|
+
});
|
|
466
|
+
if (out)
|
|
467
|
+
return out;
|
|
468
|
+
throw new ResourceNotAvailableError(this.getResourceName() + '.' + this.nestedKey, documentId + '/' + nestedId);
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* Update an array element with new data. Returns 1 if document updated 0 otherwise.
|
|
472
|
+
*
|
|
473
|
+
* @param {MongoAdapter.AnyId} documentId - The ID of the parent document.
|
|
474
|
+
* @param {MongoAdapter.AnyId} nestedId - The ID of the document to update.
|
|
475
|
+
* @param {PatchDTO<T>} input - The partial input object containing the fields to update.
|
|
476
|
+
* @param {MongoNestedService.UpdateOptions<T>} [options] - Optional update options.
|
|
477
|
+
* @returns {Promise<number>} - A promise that resolves to the number of elements updated.
|
|
478
|
+
*/
|
|
479
|
+
async updateOnly(documentId, nestedId, input, options) {
|
|
480
|
+
const info = {
|
|
481
|
+
crud: 'update',
|
|
482
|
+
method: 'update',
|
|
483
|
+
byId: true,
|
|
484
|
+
documentId,
|
|
485
|
+
nestedId,
|
|
486
|
+
options,
|
|
487
|
+
};
|
|
488
|
+
return this._intercept(async () => {
|
|
489
|
+
const documentFilter = MongoAdapter.prepareFilter([await this._getDocumentFilter(info)]);
|
|
490
|
+
const filter = MongoAdapter.prepareFilter([await this._getNestedFilter(info), options?.filter]);
|
|
491
|
+
return this._updateOnly(documentId, nestedId, input, { ...options, filter, documentFilter });
|
|
492
|
+
}, info);
|
|
493
|
+
}
|
|
494
|
+
async _updateOnly(documentId, nestedId, input, options) {
|
|
495
|
+
let filter = MongoAdapter.prepareKeyValues(nestedId, [this.nestedKey]);
|
|
496
|
+
if (options?.filter)
|
|
497
|
+
filter = MongoAdapter.prepareFilter([filter, options?.filter]);
|
|
498
|
+
return await this._updateMany(documentId, input, { ...options, filter });
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* Updates multiple array elements in document
|
|
502
|
+
*
|
|
503
|
+
* @param {MongoAdapter.AnyId} documentId - The ID of the document to update.
|
|
504
|
+
* @param {PatchDTO<T>} input - The updated data for the document(s).
|
|
505
|
+
* @param {MongoNestedService.UpdateManyOptions<T>} [options] - Additional options for the update operation.
|
|
506
|
+
* @returns {Promise<number>} - A promise that resolves to the number of documents updated.
|
|
507
|
+
*/
|
|
508
|
+
async updateMany(documentId, input, options) {
|
|
509
|
+
const info = {
|
|
510
|
+
crud: 'update',
|
|
511
|
+
method: 'updateMany',
|
|
512
|
+
documentId,
|
|
513
|
+
byId: false,
|
|
514
|
+
input,
|
|
515
|
+
options,
|
|
516
|
+
};
|
|
517
|
+
return this._intercept(async () => {
|
|
518
|
+
const documentFilter = MongoAdapter.prepareFilter([await this._getDocumentFilter(info)]);
|
|
519
|
+
const filter = MongoAdapter.prepareFilter([await this._getNestedFilter(info), options?.filter]);
|
|
520
|
+
return this._updateMany(documentId, input, { ...options, filter, documentFilter });
|
|
521
|
+
}, info);
|
|
522
|
+
}
|
|
523
|
+
async _updateMany(documentId, input, options) {
|
|
524
|
+
const encode = this.getEncoder('update');
|
|
525
|
+
const doc = encode(input, { coerce: true });
|
|
526
|
+
if (!Object.keys(doc).length)
|
|
527
|
+
return 0;
|
|
528
|
+
const matchFilter = MongoAdapter.prepareFilter([
|
|
529
|
+
MongoAdapter.prepareKeyValues(documentId, ['_id']),
|
|
530
|
+
options?.documentFilter,
|
|
531
|
+
{ [this.fieldName]: { $exists: true } },
|
|
532
|
+
]);
|
|
533
|
+
if (options?.filter) {
|
|
534
|
+
const elemMatch = MongoAdapter.prepareFilter([options?.filter], { fieldPrefix: 'elem.' });
|
|
535
|
+
options = options || {};
|
|
536
|
+
options.arrayFilters = [elemMatch];
|
|
537
|
+
}
|
|
538
|
+
const update = MongoAdapter.preparePatch(doc, {
|
|
539
|
+
fieldPrefix: this.fieldName + (options?.filter ? '.$[elem].' : '.$[].'),
|
|
540
|
+
});
|
|
541
|
+
const r = await this._dbUpdateOne(matchFilter, update, options);
|
|
542
|
+
if (options?.count)
|
|
543
|
+
return await this._count(documentId, options);
|
|
544
|
+
return r.modifiedCount || 0;
|
|
545
|
+
}
|
|
546
|
+
/**
|
|
547
|
+
* Retrieves the data type of the array field
|
|
548
|
+
*
|
|
549
|
+
* @returns {ComplexType} The complex data type of the field.
|
|
550
|
+
* @throws {NotAcceptableError} If the data type is not a ComplexType.
|
|
551
|
+
*/
|
|
552
|
+
getDataType() {
|
|
553
|
+
const t = super.getDataType().getField(this.fieldName).type;
|
|
554
|
+
if (!(t instanceof ComplexType))
|
|
555
|
+
throw new NotAcceptableError(`Data type "${t.name}" is not a ComplexType`);
|
|
556
|
+
return t;
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* Retrieves the common filter used for querying array elements.
|
|
560
|
+
* This method is mostly used for security issues like securing multi-tenant applications.
|
|
561
|
+
*
|
|
562
|
+
* @protected
|
|
563
|
+
* @returns {FilterInput | Promise<FilterInput> | undefined} The common filter or a Promise
|
|
564
|
+
* that resolves to the common filter, or undefined if not available.
|
|
565
|
+
*/
|
|
566
|
+
_getNestedFilter(args) {
|
|
567
|
+
return typeof this.$nestedFilter === 'function' ? this.$nestedFilter(args, this) : this.$nestedFilter;
|
|
568
|
+
}
|
|
569
|
+
}
|