nx-mongo 3.6.0 → 3.8.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/README.md +206 -19
- package/dist/simpleMongoHelper.d.ts +68 -15
- package/dist/simpleMongoHelper.d.ts.map +1 -1
- package/dist/simpleMongoHelper.js +200 -60
- package/dist/simpleMongoHelper.js.map +1 -1
- package/package.json +1 -1
- package/src/simpleMongoHelper.ts +254 -61
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# nx-mongo
|
|
2
2
|
|
|
3
|
-
**Version:** 3.
|
|
3
|
+
**Version:** 3.8.0
|
|
4
4
|
|
|
5
5
|
A lightweight, feature-rich MongoDB helper library for Node.js and TypeScript. Provides a simple, intuitive API for common MongoDB operations with built-in retry logic, pagination, transactions, config-driven ref mapping, and signature-based deduplication.
|
|
6
6
|
|
|
@@ -31,24 +31,39 @@ npm install nx-mongo
|
|
|
31
31
|
```typescript
|
|
32
32
|
import { SimpleMongoHelper } from 'nx-mongo';
|
|
33
33
|
|
|
34
|
-
|
|
34
|
+
// Connection string: database name is ignored/stripped automatically
|
|
35
|
+
// Use base connection string: mongodb://localhost:27017/
|
|
36
|
+
const helper = new SimpleMongoHelper('mongodb://localhost:27017/');
|
|
35
37
|
|
|
36
38
|
// Initialize connection
|
|
37
39
|
await helper.initialize();
|
|
38
40
|
|
|
39
|
-
// Insert a document
|
|
41
|
+
// Insert a document (defaults to 'admin' database)
|
|
40
42
|
await helper.insert('users', {
|
|
41
43
|
name: 'John Doe',
|
|
42
44
|
email: 'john@example.com',
|
|
43
45
|
age: 30
|
|
44
46
|
});
|
|
45
47
|
|
|
46
|
-
//
|
|
48
|
+
// Insert into a specific database
|
|
49
|
+
await helper.insert('users', {
|
|
50
|
+
name: 'Jane Doe',
|
|
51
|
+
email: 'jane@example.com',
|
|
52
|
+
age: 28
|
|
53
|
+
}, {}, 'mydb'); // Specify database name
|
|
54
|
+
|
|
55
|
+
// Find documents from 'admin' database (default)
|
|
47
56
|
const users = await helper.loadCollection('users');
|
|
48
57
|
|
|
58
|
+
// Find documents from specific database
|
|
59
|
+
const mydbUsers = await helper.loadCollection('users', {}, undefined, 'mydb');
|
|
60
|
+
|
|
49
61
|
// Find one document
|
|
50
62
|
const user = await helper.findOne('users', { email: 'john@example.com' });
|
|
51
63
|
|
|
64
|
+
// Find from specific database
|
|
65
|
+
const mydbUser = await helper.findOne('users', { email: 'jane@example.com' }, undefined, 'mydb');
|
|
66
|
+
|
|
52
67
|
// Update document
|
|
53
68
|
await helper.update(
|
|
54
69
|
'users',
|
|
@@ -56,6 +71,15 @@ await helper.update(
|
|
|
56
71
|
{ $set: { age: 31 } }
|
|
57
72
|
);
|
|
58
73
|
|
|
74
|
+
// Update in specific database
|
|
75
|
+
await helper.update(
|
|
76
|
+
'users',
|
|
77
|
+
{ email: 'jane@example.com' },
|
|
78
|
+
{ $set: { age: 29 } },
|
|
79
|
+
undefined,
|
|
80
|
+
'mydb'
|
|
81
|
+
);
|
|
82
|
+
|
|
59
83
|
// Delete document
|
|
60
84
|
await helper.delete('users', { email: 'john@example.com' });
|
|
61
85
|
|
|
@@ -63,6 +87,8 @@ await helper.delete('users', { email: 'john@example.com' });
|
|
|
63
87
|
await helper.disconnect();
|
|
64
88
|
```
|
|
65
89
|
|
|
90
|
+
**Note:** The connection string database name (if present) is automatically stripped. All operations default to the `'admin'` database unless you specify a different database name as the last parameter.
|
|
91
|
+
|
|
66
92
|
## API Reference
|
|
67
93
|
|
|
68
94
|
### Constructor
|
|
@@ -72,7 +98,8 @@ new SimpleMongoHelper(connectionString: string, retryOptions?: RetryOptions)
|
|
|
72
98
|
```
|
|
73
99
|
|
|
74
100
|
**Parameters:**
|
|
75
|
-
- `connectionString` - MongoDB connection string
|
|
101
|
+
- `connectionString` - MongoDB base connection string (database name is automatically stripped if present)
|
|
102
|
+
- Example: `'mongodb://localhost:27017/'` or `'mongodb://localhost:27017/admin'` (both work the same)
|
|
76
103
|
- `retryOptions` (optional) - Retry configuration
|
|
77
104
|
- `maxRetries?: number` - Maximum retry attempts (default: 3)
|
|
78
105
|
- `retryDelay?: number` - Initial retry delay in ms (default: 1000)
|
|
@@ -80,12 +107,15 @@ new SimpleMongoHelper(connectionString: string, retryOptions?: RetryOptions)
|
|
|
80
107
|
|
|
81
108
|
**Example:**
|
|
82
109
|
```typescript
|
|
110
|
+
// Database name in connection string is ignored/stripped
|
|
83
111
|
const helper = new SimpleMongoHelper(
|
|
84
|
-
'mongodb://localhost:27017/
|
|
112
|
+
'mongodb://localhost:27017/', // or 'mongodb://localhost:27017/admin'
|
|
85
113
|
{ maxRetries: 5, retryDelay: 2000 }
|
|
86
114
|
);
|
|
87
115
|
```
|
|
88
116
|
|
|
117
|
+
**Important:** The database name in the connection string is automatically stripped. All operations default to the `'admin'` database unless you specify a different database name per operation.
|
|
118
|
+
|
|
89
119
|
### Connection Methods
|
|
90
120
|
|
|
91
121
|
#### `testConnection(): Promise<{ success: boolean; error?: { type: string; message: string; details?: string } }>`
|
|
@@ -144,7 +174,7 @@ await helper.disconnect();
|
|
|
144
174
|
|
|
145
175
|
### Query Methods
|
|
146
176
|
|
|
147
|
-
#### `loadCollection<T>(collectionName: string, query?: Filter<T>, options?: PaginationOptions): Promise<WithId<T>[] | PaginatedResult<T>>`
|
|
177
|
+
#### `loadCollection<T>(collectionName: string, query?: Filter<T>, options?: PaginationOptions, database?: string): Promise<WithId<T>[] | PaginatedResult<T>>`
|
|
148
178
|
|
|
149
179
|
Loads documents from a collection with optional query filter and pagination.
|
|
150
180
|
|
|
@@ -155,6 +185,7 @@ Loads documents from a collection with optional query filter and pagination.
|
|
|
155
185
|
- `page?: number` - Page number (1-indexed)
|
|
156
186
|
- `limit?: number` - Documents per page
|
|
157
187
|
- `sort?: Sort` - Sort specification
|
|
188
|
+
- `database` (optional) - Database name (defaults to `'admin'`)
|
|
158
189
|
|
|
159
190
|
**Returns:**
|
|
160
191
|
- Without pagination: `WithId<T>[]`
|
|
@@ -162,9 +193,12 @@ Loads documents from a collection with optional query filter and pagination.
|
|
|
162
193
|
|
|
163
194
|
**Examples:**
|
|
164
195
|
```typescript
|
|
165
|
-
// Load all documents
|
|
196
|
+
// Load all documents from 'admin' database (default)
|
|
166
197
|
const allUsers = await helper.loadCollection('users');
|
|
167
198
|
|
|
199
|
+
// Load from specific database
|
|
200
|
+
const mydbUsers = await helper.loadCollection('users', {}, undefined, 'mydb');
|
|
201
|
+
|
|
168
202
|
// Load with query
|
|
169
203
|
const activeUsers = await helper.loadCollection('users', { active: true });
|
|
170
204
|
|
|
@@ -180,9 +214,16 @@ const result = await helper.loadCollection('users', {}, {
|
|
|
180
214
|
// result.totalPages - total pages
|
|
181
215
|
// result.hasNext - has next page
|
|
182
216
|
// result.hasPrev - has previous page
|
|
217
|
+
|
|
218
|
+
// Load with pagination from specific database
|
|
219
|
+
const mydbResult = await helper.loadCollection('users', {}, {
|
|
220
|
+
page: 1,
|
|
221
|
+
limit: 10,
|
|
222
|
+
sort: { createdAt: -1 }
|
|
223
|
+
}, 'mydb');
|
|
183
224
|
```
|
|
184
225
|
|
|
185
|
-
#### `findOne<T>(collectionName: string, query: Filter<T>, options?: { sort?: Sort; projection?: Document }): Promise<WithId<T> | null>`
|
|
226
|
+
#### `findOne<T>(collectionName: string, query: Filter<T>, options?: { sort?: Sort; projection?: Document }, database?: string): Promise<WithId<T> | null>`
|
|
186
227
|
|
|
187
228
|
Finds a single document in a collection.
|
|
188
229
|
|
|
@@ -192,6 +233,7 @@ Finds a single document in a collection.
|
|
|
192
233
|
- `options` (optional) - Find options
|
|
193
234
|
- `sort?: Sort` - Sort specification
|
|
194
235
|
- `projection?: Document` - Field projection
|
|
236
|
+
- `database` (optional) - Database name (defaults to `'admin'`)
|
|
195
237
|
|
|
196
238
|
**Example:**
|
|
197
239
|
```typescript
|
|
@@ -201,7 +243,7 @@ const latestUser = await helper.findOne('users', {}, { sort: { createdAt: -1 } }
|
|
|
201
243
|
|
|
202
244
|
### Insert Methods
|
|
203
245
|
|
|
204
|
-
#### `insert<T>(collectionName: string, data: T | T[], options?: { session?: ClientSession }): Promise<any>`
|
|
246
|
+
#### `insert<T>(collectionName: string, data: T | T[], options?: { session?: ClientSession }, database?: string): Promise<any>`
|
|
205
247
|
|
|
206
248
|
Inserts one or more documents into a collection.
|
|
207
249
|
|
|
@@ -234,7 +276,7 @@ await session.withTransaction(async () => {
|
|
|
234
276
|
|
|
235
277
|
### Update Methods
|
|
236
278
|
|
|
237
|
-
#### `update<T>(collectionName: string, filter: Filter<T>, updateData: UpdateFilter<T>, options?: { upsert?: boolean; multi?: boolean; session?: ClientSession }): Promise<any>`
|
|
279
|
+
#### `update<T>(collectionName: string, filter: Filter<T>, updateData: UpdateFilter<T>, options?: { upsert?: boolean; multi?: boolean; session?: ClientSession }, database?: string): Promise<any>`
|
|
238
280
|
|
|
239
281
|
Updates documents in a collection.
|
|
240
282
|
|
|
@@ -275,7 +317,7 @@ await helper.update(
|
|
|
275
317
|
|
|
276
318
|
### Delete Methods
|
|
277
319
|
|
|
278
|
-
#### `delete<T>(collectionName: string, filter: Filter<T>, options?: { multi?: boolean }): Promise<any>`
|
|
320
|
+
#### `delete<T>(collectionName: string, filter: Filter<T>, options?: { multi?: boolean }, database?: string): Promise<any>`
|
|
279
321
|
|
|
280
322
|
Deletes documents from a collection.
|
|
281
323
|
|
|
@@ -314,6 +356,7 @@ Merges two collections into a new target collection using various strategies (in
|
|
|
314
356
|
- `onUnmatched1` - (Deprecated: use `joinType` instead) What to do with unmatched records from collection 1: 'include' | 'skip' (default: 'include')
|
|
315
357
|
- `onUnmatched2` - (Deprecated: use `joinType` instead) What to do with unmatched records from collection 2: 'include' | 'skip' (default: 'include')
|
|
316
358
|
- `session` - Optional transaction session
|
|
359
|
+
- `database` - Optional database name (defaults to `'admin'`)
|
|
317
360
|
|
|
318
361
|
**Returns:**
|
|
319
362
|
```typescript
|
|
@@ -491,10 +534,15 @@ const result6 = await helper.mergeCollections({
|
|
|
491
534
|
|
|
492
535
|
### Count Methods
|
|
493
536
|
|
|
494
|
-
#### `countDocuments<T>(collectionName: string, query?: Filter<T
|
|
537
|
+
#### `countDocuments<T>(collectionName: string, query?: Filter<T>, database?: string): Promise<number>`
|
|
495
538
|
|
|
496
539
|
Counts documents matching a query (accurate count).
|
|
497
540
|
|
|
541
|
+
**Parameters:**
|
|
542
|
+
- `collectionName` - Name of the collection
|
|
543
|
+
- `query` (optional) - MongoDB query filter
|
|
544
|
+
- `database` (optional) - Database name (defaults to `'admin'`)
|
|
545
|
+
|
|
498
546
|
**Example:**
|
|
499
547
|
```typescript
|
|
500
548
|
const userCount = await helper.countDocuments('users');
|
|
@@ -512,10 +560,15 @@ const estimatedCount = await helper.estimatedDocumentCount('users');
|
|
|
512
560
|
|
|
513
561
|
### Aggregation Methods
|
|
514
562
|
|
|
515
|
-
#### `aggregate<T>(collectionName: string, pipeline: Document[]): Promise<T[]>`
|
|
563
|
+
#### `aggregate<T>(collectionName: string, pipeline: Document[], database?: string): Promise<T[]>`
|
|
516
564
|
|
|
517
565
|
Runs an aggregation pipeline on a collection.
|
|
518
566
|
|
|
567
|
+
**Parameters:**
|
|
568
|
+
- `collectionName` - Name of the collection
|
|
569
|
+
- `pipeline` - Array of aggregation pipeline stages
|
|
570
|
+
- `database` (optional) - Database name (defaults to `'admin'`)
|
|
571
|
+
|
|
519
572
|
**Example:**
|
|
520
573
|
```typescript
|
|
521
574
|
const result = await helper.aggregate('orders', [
|
|
@@ -531,10 +584,16 @@ const result = await helper.aggregate('orders', [
|
|
|
531
584
|
|
|
532
585
|
### Index Methods
|
|
533
586
|
|
|
534
|
-
#### `createIndex(collectionName: string, indexSpec: IndexSpecification, options?: CreateIndexesOptions): Promise<string>`
|
|
587
|
+
#### `createIndex(collectionName: string, indexSpec: IndexSpecification, options?: CreateIndexesOptions, database?: string): Promise<string>`
|
|
535
588
|
|
|
536
589
|
Creates an index on a collection.
|
|
537
590
|
|
|
591
|
+
**Parameters:**
|
|
592
|
+
- `collectionName` - Name of the collection
|
|
593
|
+
- `indexSpec` - Index specification
|
|
594
|
+
- `options` (optional) - Index creation options
|
|
595
|
+
- `database` (optional) - Database name (defaults to `'admin'`)
|
|
596
|
+
|
|
538
597
|
**Example:**
|
|
539
598
|
```typescript
|
|
540
599
|
// Simple index
|
|
@@ -547,19 +606,28 @@ await helper.createIndex('users', { email: 1 }, { unique: true });
|
|
|
547
606
|
await helper.createIndex('users', { email: 1, createdAt: -1 });
|
|
548
607
|
```
|
|
549
608
|
|
|
550
|
-
#### `dropIndex(collectionName: string, indexName: string): Promise<any>`
|
|
609
|
+
#### `dropIndex(collectionName: string, indexName: string, database?: string): Promise<any>`
|
|
551
610
|
|
|
552
611
|
Drops an index from a collection.
|
|
553
612
|
|
|
613
|
+
**Parameters:**
|
|
614
|
+
- `collectionName` - Name of the collection
|
|
615
|
+
- `indexName` - Name of the index to drop
|
|
616
|
+
- `database` (optional) - Database name (defaults to `'admin'`)
|
|
617
|
+
|
|
554
618
|
**Example:**
|
|
555
619
|
```typescript
|
|
556
620
|
await helper.dropIndex('users', 'email_1');
|
|
557
621
|
```
|
|
558
622
|
|
|
559
|
-
#### `listIndexes(collectionName: string): Promise<Document[]>`
|
|
623
|
+
#### `listIndexes(collectionName: string, database?: string): Promise<Document[]>`
|
|
560
624
|
|
|
561
625
|
Lists all indexes on a collection.
|
|
562
626
|
|
|
627
|
+
**Parameters:**
|
|
628
|
+
- `collectionName` - Name of the collection
|
|
629
|
+
- `database` (optional) - Database name (defaults to `'admin'`)
|
|
630
|
+
|
|
563
631
|
**Example:**
|
|
564
632
|
```typescript
|
|
565
633
|
const indexes = await helper.listIndexes('users');
|
|
@@ -621,6 +689,11 @@ interface HelperConfig {
|
|
|
621
689
|
uniqueIndexKeys?: string[]; // Unique index keys (default: ["provider","key"])
|
|
622
690
|
provider?: string; // Default provider namespace for this helper instance
|
|
623
691
|
};
|
|
692
|
+
databases?: Array<{
|
|
693
|
+
ref: string; // Reference identifier
|
|
694
|
+
type: string; // Type identifier
|
|
695
|
+
database: string; // Database name to use
|
|
696
|
+
}>;
|
|
624
697
|
}
|
|
625
698
|
```
|
|
626
699
|
|
|
@@ -669,15 +742,101 @@ Sets or updates the configuration for ref-based operations.
|
|
|
669
742
|
helper.useConfig(config);
|
|
670
743
|
```
|
|
671
744
|
|
|
745
|
+
### Database Selection via Ref/Type Map
|
|
746
|
+
|
|
747
|
+
The helper supports config-driven database selection using `ref` and `type` parameters. This allows you to map logical identifiers to database names without hardcoding them in your application code.
|
|
748
|
+
|
|
749
|
+
**Configuration:**
|
|
750
|
+
|
|
751
|
+
```typescript
|
|
752
|
+
const config = {
|
|
753
|
+
// ... inputs, outputs, etc.
|
|
754
|
+
databases: [
|
|
755
|
+
{ ref: "app1", type: "production", database: "app1_prod" },
|
|
756
|
+
{ ref: "app1", type: "staging", database: "app1_staging" },
|
|
757
|
+
{ ref: "app2", type: "production", database: "app2_prod" },
|
|
758
|
+
{ ref: "app2", type: "staging", database: "app2_staging" },
|
|
759
|
+
]
|
|
760
|
+
};
|
|
761
|
+
```
|
|
762
|
+
|
|
763
|
+
**Usage in CRUD Operations:**
|
|
764
|
+
|
|
765
|
+
All CRUD operations now support optional `ref` and `type` parameters for automatic database resolution:
|
|
766
|
+
|
|
767
|
+
```typescript
|
|
768
|
+
// Priority 1: Direct database parameter (highest priority)
|
|
769
|
+
await helper.insert('users', { name: 'John' }, {}, 'mydb');
|
|
770
|
+
|
|
771
|
+
// Priority 2: Using ref + type (exact match)
|
|
772
|
+
await helper.insert('users', { name: 'John' }, {}, undefined, 'app1', 'production');
|
|
773
|
+
// Resolves to 'app1_prod' database
|
|
774
|
+
|
|
775
|
+
// Priority 3: Using ref alone (must have exactly one match)
|
|
776
|
+
await helper.insert('users', { name: 'John' }, {}, undefined, 'app1');
|
|
777
|
+
// Throws error if multiple matches found
|
|
778
|
+
|
|
779
|
+
// Priority 4: Using type alone (must have exactly one match)
|
|
780
|
+
await helper.insert('users', { name: 'John' }, {}, undefined, undefined, 'production');
|
|
781
|
+
// Throws error if multiple matches found
|
|
782
|
+
```
|
|
783
|
+
|
|
784
|
+
**Database Resolution Priority:**
|
|
785
|
+
|
|
786
|
+
1. **Direct `database` parameter** - If provided, it's used immediately (highest priority)
|
|
787
|
+
2. **`ref` + `type`** - If both provided, finds exact match in databases map
|
|
788
|
+
3. **`ref` alone** - If only ref provided, finds entries matching ref (must be exactly one)
|
|
789
|
+
4. **`type` alone** - If only type provided, finds entries matching type (must be exactly one)
|
|
790
|
+
5. **Default** - If none provided, defaults to `'admin'` database
|
|
791
|
+
|
|
792
|
+
**Error Handling:**
|
|
793
|
+
|
|
794
|
+
- If no match found: throws error with descriptive message
|
|
795
|
+
- If multiple matches found: throws error suggesting to use additional parameter to narrow down
|
|
796
|
+
|
|
797
|
+
**Example:**
|
|
798
|
+
|
|
799
|
+
```typescript
|
|
800
|
+
const config = {
|
|
801
|
+
databases: [
|
|
802
|
+
{ ref: "tenant1", type: "prod", database: "tenant1_prod" },
|
|
803
|
+
{ ref: "tenant1", type: "dev", database: "tenant1_dev" },
|
|
804
|
+
{ ref: "tenant2", type: "prod", database: "tenant2_prod" },
|
|
805
|
+
]
|
|
806
|
+
};
|
|
807
|
+
|
|
808
|
+
const helper = new SimpleMongoHelper('mongodb://localhost:27017/', undefined, config);
|
|
809
|
+
await helper.initialize();
|
|
810
|
+
|
|
811
|
+
// Use ref + type for exact match
|
|
812
|
+
await helper.insert('users', { name: 'John' }, {}, undefined, 'tenant1', 'prod');
|
|
813
|
+
// Uses 'tenant1_prod' database
|
|
814
|
+
|
|
815
|
+
// Use ref alone (only works if exactly one match)
|
|
816
|
+
// This would throw error because tenant1 has 2 matches (prod and dev)
|
|
817
|
+
// await helper.insert('users', { name: 'John' }, {}, undefined, 'tenant1');
|
|
818
|
+
|
|
819
|
+
// Use type alone (only works if exactly one match)
|
|
820
|
+
// This would throw error because 'prod' has 2 matches (tenant1 and tenant2)
|
|
821
|
+
// await helper.insert('users', { name: 'John' }, {}, undefined, undefined, 'prod');
|
|
822
|
+
```
|
|
823
|
+
|
|
672
824
|
### Ref-based Operations
|
|
673
825
|
|
|
674
|
-
#### `loadByRef<T>(ref: string, options?: PaginationOptions & { session?: ClientSession }): Promise<WithId<T>[] | PaginatedResult<T>>`
|
|
826
|
+
#### `loadByRef<T>(ref: string, options?: PaginationOptions & { session?: ClientSession; database?: string; ref?: string; type?: string }): Promise<WithId<T>[] | PaginatedResult<T>>`
|
|
675
827
|
|
|
676
828
|
Loads data from a collection using a ref name from the configuration.
|
|
677
829
|
|
|
678
830
|
**Parameters:**
|
|
679
831
|
- `ref` - Application-level reference name (must exist in config.inputs)
|
|
680
832
|
- `options` (optional) - Pagination and session options
|
|
833
|
+
- `page?: number` - Page number (1-indexed)
|
|
834
|
+
- `limit?: number` - Documents per page
|
|
835
|
+
- `sort?: Sort` - Sort specification
|
|
836
|
+
- `session?: ClientSession` - Transaction session
|
|
837
|
+
- `database?: string` - Database name (defaults to `'admin'`)
|
|
838
|
+
- `ref?: string` - Optional ref for database resolution
|
|
839
|
+
- `type?: string` - Optional type for database resolution
|
|
681
840
|
|
|
682
841
|
**Example:**
|
|
683
842
|
|
|
@@ -694,7 +853,7 @@ const result = await helper.loadByRef('topology', {
|
|
|
694
853
|
});
|
|
695
854
|
```
|
|
696
855
|
|
|
697
|
-
#### `writeByRef(ref: string, documents: any[], options?: { session?: ClientSession; ensureIndex?: boolean }): Promise<WriteByRefResult>`
|
|
856
|
+
#### `writeByRef(ref: string, documents: any[], options?: { session?: ClientSession; ensureIndex?: boolean; database?: string; ref?: string; type?: string }): Promise<WriteByRefResult>`
|
|
698
857
|
|
|
699
858
|
Writes documents to a collection using a ref name from the configuration. Supports signature-based deduplication and append/replace modes.
|
|
700
859
|
|
|
@@ -704,6 +863,9 @@ Writes documents to a collection using a ref name from the configuration. Suppor
|
|
|
704
863
|
- `options` (optional) - Write options
|
|
705
864
|
- `session?: ClientSession` - Transaction session
|
|
706
865
|
- `ensureIndex?: boolean` - Whether to ensure signature index exists (default: true)
|
|
866
|
+
- `database?: string` - Database name (defaults to `'admin'`)
|
|
867
|
+
- `ref?: string` - Optional ref for database resolution
|
|
868
|
+
- `type?: string` - Optional type for database resolution
|
|
707
869
|
|
|
708
870
|
**Returns:**
|
|
709
871
|
|
|
@@ -732,6 +894,15 @@ await helper.writeByRef('prioritizedPaths', prioritizedDocs);
|
|
|
732
894
|
|
|
733
895
|
Writes documents to a collection and optionally marks a stage as complete atomically. See the [Progress Tracking](#progress-tracking) section for details and examples.
|
|
734
896
|
|
|
897
|
+
**Parameters:**
|
|
898
|
+
- `ref` - Application-level reference name (must exist in config.outputs)
|
|
899
|
+
- `documents` - Array of documents to write
|
|
900
|
+
- `options` (optional) - Write and completion options
|
|
901
|
+
- `session?: ClientSession` - Transaction session
|
|
902
|
+
- `ensureIndex?: boolean` - Whether to ensure signature index exists (default: true)
|
|
903
|
+
- `database?: string` - Database name (defaults to `'admin'`)
|
|
904
|
+
- `complete?: object` - Stage completion information (optional)
|
|
905
|
+
|
|
735
906
|
**Example:**
|
|
736
907
|
|
|
737
908
|
```typescript
|
|
@@ -1323,6 +1494,22 @@ Contributions are welcome! Please feel free to submit a Pull Request.
|
|
|
1323
1494
|
|
|
1324
1495
|
## Changelog
|
|
1325
1496
|
|
|
1497
|
+
### 3.8.0
|
|
1498
|
+
- **Database selection via ref/type map**: Added config-driven database selection using `ref` and `type` parameters
|
|
1499
|
+
- Added `databases` array to `HelperConfig` for mapping ref/type combinations to database names
|
|
1500
|
+
- All CRUD operations now support optional `ref` and `type` parameters for automatic database resolution
|
|
1501
|
+
- Database resolution priority: direct `database` parameter > `ref` + `type` > `ref` alone > `type` alone
|
|
1502
|
+
- Throws descriptive errors when no match or multiple matches found in database map
|
|
1503
|
+
- Updated Progress API to support database resolution via ref/type
|
|
1504
|
+
- Updated `loadByRef`, `writeByRef`, `writeStage`, and `mergeCollections` to support database map resolution
|
|
1505
|
+
|
|
1506
|
+
### 3.7.0
|
|
1507
|
+
- **Separated database from connection string**: Database name is now specified per operation, not in connection string
|
|
1508
|
+
- **Multi-database support**: All operations accept optional `database` parameter (defaults to `'admin'`)
|
|
1509
|
+
- Connection string database name is automatically stripped if present (e.g., `mongodb://localhost:27017/admin` becomes `mongodb://localhost:27017/`)
|
|
1510
|
+
- Updated all methods (`insert`, `update`, `delete`, `loadCollection`, `findOne`, `countDocuments`, `aggregate`, `createIndex`, `dropIndex`, `listIndexes`, `writeByRef`, `loadByRef`, `mergeCollections`, `writeStage`, and progress API) to support per-operation database selection
|
|
1511
|
+
- **Breaking change**: No backward compatibility - all code must be updated to use new database parameter
|
|
1512
|
+
|
|
1326
1513
|
### 3.6.0
|
|
1327
1514
|
- **Automatic connection cleanup**: Connections now automatically close on app exit (SIGINT, SIGTERM, beforeExit)
|
|
1328
1515
|
- **Multi-instance support**: Global registry handles multiple `SimpleMongoHelper` instances gracefully
|
|
@@ -40,6 +40,11 @@ export interface HelperConfig {
|
|
|
40
40
|
uniqueIndexKeys?: string[];
|
|
41
41
|
provider?: string;
|
|
42
42
|
};
|
|
43
|
+
databases?: Array<{
|
|
44
|
+
ref: string;
|
|
45
|
+
type: string;
|
|
46
|
+
database: string;
|
|
47
|
+
}>;
|
|
43
48
|
}
|
|
44
49
|
export interface WriteByRefResult {
|
|
45
50
|
inserted: number;
|
|
@@ -75,6 +80,9 @@ export interface StageRecord extends StageIdentity {
|
|
|
75
80
|
}
|
|
76
81
|
export type ProgressSessionOptions = {
|
|
77
82
|
session?: ClientSession;
|
|
83
|
+
database?: string;
|
|
84
|
+
ref?: string;
|
|
85
|
+
type?: string;
|
|
78
86
|
};
|
|
79
87
|
export interface ProgressAPI {
|
|
80
88
|
isCompleted(key: string, options?: ProgressSessionOptions & {
|
|
@@ -101,6 +109,9 @@ export interface ProgressAPI {
|
|
|
101
109
|
export interface WriteStageOptions {
|
|
102
110
|
ensureIndex?: boolean;
|
|
103
111
|
session?: ClientSession;
|
|
112
|
+
database?: string;
|
|
113
|
+
ref?: string;
|
|
114
|
+
type?: string;
|
|
104
115
|
complete?: {
|
|
105
116
|
key: string;
|
|
106
117
|
process?: string;
|
|
@@ -126,6 +137,9 @@ export interface MergeCollectionsOptions {
|
|
|
126
137
|
onUnmatched1?: 'include' | 'skip';
|
|
127
138
|
onUnmatched2?: 'include' | 'skip';
|
|
128
139
|
session?: ClientSession;
|
|
140
|
+
database?: string;
|
|
141
|
+
ref?: string;
|
|
142
|
+
type?: string;
|
|
129
143
|
}
|
|
130
144
|
export interface MergeCollectionsResult {
|
|
131
145
|
merged: number;
|
|
@@ -207,7 +221,7 @@ export declare class SimpleMongoHelper {
|
|
|
207
221
|
* @returns Array of documents matching the query or paginated result
|
|
208
222
|
* @throws Error if not initialized or if query fails
|
|
209
223
|
*/
|
|
210
|
-
loadCollection<T extends Document = Document>(collectionName: string, query?: Filter<T>, options?: PaginationOptions): Promise<WithId<T>[] | PaginatedResult<T>>;
|
|
224
|
+
loadCollection<T extends Document = Document>(collectionName: string, query?: Filter<T>, options?: PaginationOptions, database?: string, ref?: string, type?: string): Promise<WithId<T>[] | PaginatedResult<T>>;
|
|
211
225
|
/**
|
|
212
226
|
* Finds a single document in a collection.
|
|
213
227
|
* @param collectionName - Name of the collection to query
|
|
@@ -219,7 +233,7 @@ export declare class SimpleMongoHelper {
|
|
|
219
233
|
findOne<T extends Document = Document>(collectionName: string, query: Filter<T>, options?: {
|
|
220
234
|
sort?: Sort;
|
|
221
235
|
projection?: Document;
|
|
222
|
-
}): Promise<WithId<T> | null>;
|
|
236
|
+
}, database?: string, ref?: string, type?: string): Promise<WithId<T> | null>;
|
|
223
237
|
/**
|
|
224
238
|
* Inserts data into a collection.
|
|
225
239
|
* @param collectionName - Name of the collection to insert into
|
|
@@ -230,7 +244,7 @@ export declare class SimpleMongoHelper {
|
|
|
230
244
|
*/
|
|
231
245
|
insert<T extends Document = Document>(collectionName: string, data: OptionalUnlessRequiredId<T> | OptionalUnlessRequiredId<T>[], options?: {
|
|
232
246
|
session?: ClientSession;
|
|
233
|
-
}): Promise<any>;
|
|
247
|
+
}, database?: string, ref?: string, type?: string): Promise<any>;
|
|
234
248
|
/**
|
|
235
249
|
* Updates records in a collection.
|
|
236
250
|
* @param collectionName - Name of the collection to update
|
|
@@ -244,7 +258,7 @@ export declare class SimpleMongoHelper {
|
|
|
244
258
|
upsert?: boolean;
|
|
245
259
|
multi?: boolean;
|
|
246
260
|
session?: ClientSession;
|
|
247
|
-
}): Promise<any>;
|
|
261
|
+
}, database?: string, ref?: string, type?: string): Promise<any>;
|
|
248
262
|
/**
|
|
249
263
|
* Deletes documents from a collection.
|
|
250
264
|
* @param collectionName - Name of the collection to delete from
|
|
@@ -255,7 +269,7 @@ export declare class SimpleMongoHelper {
|
|
|
255
269
|
*/
|
|
256
270
|
delete<T extends Document = Document>(collectionName: string, filter: Filter<T>, options?: {
|
|
257
271
|
multi?: boolean;
|
|
258
|
-
}): Promise<any>;
|
|
272
|
+
}, database?: string, ref?: string, type?: string): Promise<any>;
|
|
259
273
|
/**
|
|
260
274
|
* Counts documents in a collection matching a query.
|
|
261
275
|
* @param collectionName - Name of the collection to count
|
|
@@ -263,14 +277,14 @@ export declare class SimpleMongoHelper {
|
|
|
263
277
|
* @returns Number of documents matching the query
|
|
264
278
|
* @throws Error if not initialized or if count fails
|
|
265
279
|
*/
|
|
266
|
-
countDocuments<T extends Document = Document>(collectionName: string, query?: Filter<T
|
|
280
|
+
countDocuments<T extends Document = Document>(collectionName: string, query?: Filter<T>, database?: string, ref?: string, type?: string): Promise<number>;
|
|
267
281
|
/**
|
|
268
282
|
* Gets an estimated document count for a collection (faster but less accurate).
|
|
269
283
|
* @param collectionName - Name of the collection to count
|
|
270
284
|
* @returns Estimated number of documents
|
|
271
285
|
* @throws Error if not initialized or if count fails
|
|
272
286
|
*/
|
|
273
|
-
estimatedDocumentCount(collectionName: string): Promise<number>;
|
|
287
|
+
estimatedDocumentCount(collectionName: string, database?: string, ref?: string, type?: string): Promise<number>;
|
|
274
288
|
/**
|
|
275
289
|
* Runs an aggregation pipeline on a collection.
|
|
276
290
|
* @param collectionName - Name of the collection to aggregate
|
|
@@ -278,7 +292,7 @@ export declare class SimpleMongoHelper {
|
|
|
278
292
|
* @returns Array of aggregated results
|
|
279
293
|
* @throws Error if not initialized or if aggregation fails
|
|
280
294
|
*/
|
|
281
|
-
aggregate<T extends Document = Document>(collectionName: string, pipeline: Document[]): Promise<T[]>;
|
|
295
|
+
aggregate<T extends Document = Document>(collectionName: string, pipeline: Document[], database?: string, ref?: string, type?: string): Promise<T[]>;
|
|
282
296
|
/**
|
|
283
297
|
* Creates an index on a collection.
|
|
284
298
|
* @param collectionName - Name of the collection
|
|
@@ -287,7 +301,7 @@ export declare class SimpleMongoHelper {
|
|
|
287
301
|
* @returns Index name
|
|
288
302
|
* @throws Error if not initialized or if index creation fails
|
|
289
303
|
*/
|
|
290
|
-
createIndex(collectionName: string, indexSpec: IndexSpecification, options?: CreateIndexesOptions): Promise<string>;
|
|
304
|
+
createIndex(collectionName: string, indexSpec: IndexSpecification, options?: CreateIndexesOptions, database?: string, ref?: string, type?: string): Promise<string>;
|
|
291
305
|
/**
|
|
292
306
|
* Drops an index from a collection.
|
|
293
307
|
* @param collectionName - Name of the collection
|
|
@@ -295,14 +309,14 @@ export declare class SimpleMongoHelper {
|
|
|
295
309
|
* @returns Result object
|
|
296
310
|
* @throws Error if not initialized or if index drop fails
|
|
297
311
|
*/
|
|
298
|
-
dropIndex(collectionName: string, indexName: string): Promise<any>;
|
|
312
|
+
dropIndex(collectionName: string, indexName: string, database?: string, ref?: string, type?: string): Promise<any>;
|
|
299
313
|
/**
|
|
300
314
|
* Lists all indexes on a collection.
|
|
301
315
|
* @param collectionName - Name of the collection
|
|
302
316
|
* @returns Array of index information
|
|
303
317
|
* @throws Error if not initialized or if listing fails
|
|
304
318
|
*/
|
|
305
|
-
listIndexes(collectionName: string): Promise<Document[]>;
|
|
319
|
+
listIndexes(collectionName: string, database?: string, ref?: string, type?: string): Promise<Document[]>;
|
|
306
320
|
/**
|
|
307
321
|
* Starts a new client session for transactions.
|
|
308
322
|
* @returns Client session
|
|
@@ -325,6 +339,9 @@ export declare class SimpleMongoHelper {
|
|
|
325
339
|
*/
|
|
326
340
|
loadByRef<T extends Document = Document>(ref: string, options?: PaginationOptions & {
|
|
327
341
|
session?: ClientSession;
|
|
342
|
+
database?: string;
|
|
343
|
+
ref?: string;
|
|
344
|
+
type?: string;
|
|
328
345
|
}): Promise<WithId<T>[] | PaginatedResult<T>>;
|
|
329
346
|
/**
|
|
330
347
|
* Ensures a unique index exists on the _sig field for signature-based deduplication.
|
|
@@ -338,6 +355,9 @@ export declare class SimpleMongoHelper {
|
|
|
338
355
|
ensureSignatureIndex(collectionName: string, options?: {
|
|
339
356
|
fieldName?: string;
|
|
340
357
|
unique?: boolean;
|
|
358
|
+
database?: string;
|
|
359
|
+
ref?: string;
|
|
360
|
+
type?: string;
|
|
341
361
|
}): Promise<EnsureSignatureIndexResult>;
|
|
342
362
|
/**
|
|
343
363
|
* Writes documents to a collection using a ref name from the configuration.
|
|
@@ -353,6 +373,9 @@ export declare class SimpleMongoHelper {
|
|
|
353
373
|
writeByRef(ref: string, documents: any[], options?: {
|
|
354
374
|
session?: ClientSession;
|
|
355
375
|
ensureIndex?: boolean;
|
|
376
|
+
database?: string;
|
|
377
|
+
ref?: string;
|
|
378
|
+
type?: string;
|
|
356
379
|
}): Promise<WriteByRefResult>;
|
|
357
380
|
/**
|
|
358
381
|
* Writes documents to a collection using a ref name and optionally marks a stage as complete.
|
|
@@ -400,10 +423,40 @@ export declare class SimpleMongoHelper {
|
|
|
400
423
|
*/
|
|
401
424
|
getDb(): Db;
|
|
402
425
|
/**
|
|
403
|
-
*
|
|
404
|
-
* @param connectionString - MongoDB connection string
|
|
405
|
-
* @returns
|
|
426
|
+
* Strips database name from MongoDB connection string, returning base connection string.
|
|
427
|
+
* @param connectionString - MongoDB connection string (may include database name)
|
|
428
|
+
* @returns Base connection string without database name
|
|
429
|
+
* @example
|
|
430
|
+
* stripDatabaseFromConnectionString('mongodb://localhost:27017/admin')
|
|
431
|
+
* // Returns: 'mongodb://localhost:27017/'
|
|
432
|
+
*/
|
|
433
|
+
private stripDatabaseFromConnectionString;
|
|
434
|
+
/**
|
|
435
|
+
* Resolves the database name from provided options using the databases config map.
|
|
436
|
+
* Priority: database > ref+type > ref > type
|
|
437
|
+
* @param options - Options containing database, ref, and/or type
|
|
438
|
+
* @returns Resolved database name or undefined (will default to 'admin')
|
|
439
|
+
* @throws Error if no match found or multiple matches found
|
|
440
|
+
* @internal
|
|
441
|
+
*/
|
|
442
|
+
private resolveDatabase;
|
|
443
|
+
/**
|
|
444
|
+
* Gets a database instance by name. Defaults to 'admin' if no name provided.
|
|
445
|
+
* @param databaseName - Optional database name (defaults to 'admin')
|
|
446
|
+
* @returns Database instance
|
|
447
|
+
* @throws Error if client is not initialized
|
|
448
|
+
* @internal
|
|
449
|
+
*/
|
|
450
|
+
private getDatabase;
|
|
451
|
+
/**
|
|
452
|
+
* Gets a database instance by name. Defaults to 'admin' if no name provided.
|
|
453
|
+
* Public method for use by ProgressAPIImpl.
|
|
454
|
+
* @param databaseName - Optional database name (defaults to 'admin')
|
|
455
|
+
* @param ref - Optional ref for database resolution
|
|
456
|
+
* @param type - Optional type for database resolution
|
|
457
|
+
* @returns Database instance
|
|
458
|
+
* @throws Error if client is not initialized
|
|
406
459
|
*/
|
|
407
|
-
|
|
460
|
+
getDatabaseByName(databaseName?: string, ref?: string, type?: string): Db;
|
|
408
461
|
}
|
|
409
462
|
//# sourceMappingURL=simpleMongoHelper.d.ts.map
|