0
# Model Operations
1
2
Model class providing static methods for CRUD operations, queries, aggregation, and document management with full MongoDB feature support.
3
4
## Capabilities
5
6
### Model Creation
7
8
Define models from schemas and manage model registration.
9
10
```javascript { .api }
11
/**
12
* Creates or retrieves a model
13
* @param name - Model name
14
* @param schema - Schema definition
15
* @param collection - Collection name (optional)
16
* @param options - Compilation options
17
* @returns Model constructor
18
*/
19
mongoose.model<T>(
20
name: string,
21
schema?: Schema<T>,
22
collection?: string,
23
options?: CompileModelOptions
24
): Model<T>;
25
26
/**
27
* Remove a model from Mongoose
28
* @param name - Model name to remove
29
* @returns Mongoose instance
30
*/
31
mongoose.deleteModel(name: string): typeof mongoose;
32
33
/**
34
* Get array of registered model names
35
* @returns Array of model names
36
*/
37
mongoose.modelNames(): string[];
38
39
interface CompileModelOptions {
40
/** Overwrite existing model */
41
overwriteModels?: boolean;
42
43
/** Connection to use */
44
connection?: Connection;
45
}
46
```
47
48
**Usage Examples:**
49
50
```javascript
51
const mongoose = require('mongoose');
52
53
// Define schema
54
const userSchema = new mongoose.Schema({
55
name: String,
56
email: String,
57
age: Number
58
});
59
60
// Create model
61
const User = mongoose.model('User', userSchema);
62
63
// Create model with custom collection name
64
const Admin = mongoose.model('Admin', userSchema, 'administrators');
65
66
// Check registered models
67
console.log(mongoose.modelNames()); // ['User', 'Admin']
68
69
// Remove model
70
mongoose.deleteModel('Admin');
71
```
72
73
### Document Creation
74
75
Create and insert new documents into the database.
76
77
```javascript { .api }
78
interface Model<T> {
79
/**
80
* Create and save documents
81
* @param docs - Document data or array of document data
82
* @returns Promise resolving to created document(s)
83
*/
84
static create<T>(docs: T | T[]): Promise<T extends any[] ? T : T>;
85
86
/**
87
* Insert multiple documents
88
* @param docs - Array of document data
89
* @param options - Insert options
90
* @returns Promise resolving to inserted documents
91
*/
92
static insertMany<T>(
93
docs: T[],
94
options?: InsertManyOptions
95
): Promise<T[]>;
96
97
/**
98
* Create document instance without saving
99
* @param doc - Document data
100
* @returns New document instance
101
*/
102
constructor(doc?: Partial<T>): T;
103
}
104
105
interface InsertManyOptions {
106
/** Continue inserting on error */
107
ordered?: boolean;
108
109
/** Raw result instead of documents */
110
rawResult?: boolean;
111
112
/** Skip validation */
113
skipValidation?: boolean;
114
115
/** Lean mode */
116
lean?: boolean;
117
}
118
```
119
120
**Usage Examples:**
121
122
```javascript
123
// Create single document
124
const user = await User.create({
125
name: 'John Doe',
126
email: 'john@example.com',
127
age: 30
128
});
129
130
// Create multiple documents
131
const users = await User.create([
132
{ name: 'Alice', email: 'alice@example.com', age: 25 },
133
{ name: 'Bob', email: 'bob@example.com', age: 35 }
134
]);
135
136
// Insert many with options
137
const results = await User.insertMany(userData, {
138
ordered: false,
139
skipValidation: true
140
});
141
142
// Create instance without saving
143
const newUser = new User({ name: 'Jane' });
144
await newUser.save();
145
```
146
147
### Query Operations
148
149
Find and retrieve documents with flexible query conditions.
150
151
```javascript { .api }
152
interface Model<T> {
153
/**
154
* Find multiple documents
155
* @param filter - Query conditions
156
* @param projection - Fields to include/exclude
157
* @returns Query instance
158
*/
159
static find<T>(
160
filter?: FilterQuery<T>,
161
projection?: ProjectionType<T>
162
): Query<T[], T>;
163
164
/**
165
* Find single document
166
* @param filter - Query conditions
167
* @param projection - Fields to include/exclude
168
* @returns Query instance
169
*/
170
static findOne<T>(
171
filter?: FilterQuery<T>,
172
projection?: ProjectionType<T>
173
): Query<T | null, T>;
174
175
/**
176
* Find document by ID
177
* @param id - Document ID
178
* @param projection - Fields to include/exclude
179
* @returns Query instance
180
*/
181
static findById<T>(
182
id: any,
183
projection?: ProjectionType<T>
184
): Query<T | null, T>;
185
186
/**
187
* Check if document exists
188
* @param filter - Query conditions
189
* @returns Promise resolving to document ID or null
190
*/
191
static exists<T>(filter: FilterQuery<T>): Promise<{ _id: any } | null>;
192
193
/**
194
* Count documents matching filter
195
* @param filter - Query conditions
196
* @returns Promise resolving to count
197
*/
198
static countDocuments<T>(filter?: FilterQuery<T>): Promise<number>;
199
200
/**
201
* Get estimated document count
202
* @param options - Count options
203
* @returns Promise resolving to estimated count
204
*/
205
static estimatedDocumentCount<T>(options?: any): Promise<number>;
206
207
/**
208
* Get distinct values for a field
209
* @param field - Field name
210
* @param filter - Query conditions
211
* @returns Promise resolving to distinct values array
212
*/
213
static distinct<T>(field: string, filter?: FilterQuery<T>): Promise<any[]>;
214
}
215
```
216
217
**Usage Examples:**
218
219
```javascript
220
// Find all users
221
const users = await User.find();
222
223
// Find with conditions
224
const adults = await User.find({ age: { $gte: 18 } });
225
226
// Find with projection
227
const userNames = await User.find({}, 'name email');
228
229
// Find one document
230
const user = await User.findOne({ email: 'john@example.com' });
231
232
// Find by ID
233
const user = await User.findById('507f1f77bcf86cd799439011');
234
235
// Check existence
236
const exists = await User.exists({ email: 'john@example.com' });
237
238
// Count documents
239
const count = await User.countDocuments({ age: { $gte: 18 } });
240
241
// Get distinct values
242
const ages = await User.distinct('age');
243
```
244
245
### Update Operations
246
247
Modify existing documents in the database.
248
249
```javascript { .api }
250
interface Model<T> {
251
/**
252
* Update single document
253
* @param filter - Query conditions
254
* @param update - Update operations
255
* @param options - Update options
256
* @returns Promise resolving to update result
257
*/
258
static updateOne<T>(
259
filter: FilterQuery<T>,
260
update: UpdateQuery<T>,
261
options?: UpdateOptions
262
): Promise<UpdateResult>;
263
264
/**
265
* Update multiple documents
266
* @param filter - Query conditions
267
* @param update - Update operations
268
* @param options - Update options
269
* @returns Promise resolving to update result
270
*/
271
static updateMany<T>(
272
filter: FilterQuery<T>,
273
update: UpdateQuery<T>,
274
options?: UpdateOptions
275
): Promise<UpdateResult>;
276
277
/**
278
* Replace single document
279
* @param filter - Query conditions
280
* @param replacement - Replacement document
281
* @param options - Replace options
282
* @returns Promise resolving to update result
283
*/
284
static replaceOne<T>(
285
filter: FilterQuery<T>,
286
replacement: Partial<T>,
287
options?: ReplaceOptions
288
): Promise<UpdateResult>;
289
290
/**
291
* Find and update single document
292
* @param filter - Query conditions
293
* @param update - Update operations
294
* @param options - Update options
295
* @returns Promise resolving to updated document
296
*/
297
static findOneAndUpdate<T>(
298
filter: FilterQuery<T>,
299
update: UpdateQuery<T>,
300
options?: FindOneAndUpdateOptions
301
): Promise<T | null>;
302
303
/**
304
* Find by ID and update
305
* @param id - Document ID
306
* @param update - Update operations
307
* @param options - Update options
308
* @returns Promise resolving to updated document
309
*/
310
static findByIdAndUpdate<T>(
311
id: any,
312
update: UpdateQuery<T>,
313
options?: FindOneAndUpdateOptions
314
): Promise<T | null>;
315
}
316
317
interface UpdateOptions {
318
/** Create document if not found */
319
upsert?: boolean;
320
321
/** Return updated document */
322
new?: boolean;
323
324
/** Run validators on update */
325
runValidators?: boolean;
326
327
/** Set default values on upsert */
328
setDefaultsOnInsert?: boolean;
329
330
/** Fields to return */
331
select?: string | object;
332
333
/** Write concern */
334
writeConcern?: any;
335
336
/** Array filters for update */
337
arrayFilters?: any[];
338
}
339
```
340
341
**Usage Examples:**
342
343
```javascript
344
// Update single document
345
const result = await User.updateOne(
346
{ email: 'john@example.com' },
347
{ $set: { age: 31 } }
348
);
349
350
// Update multiple documents
351
await User.updateMany(
352
{ age: { $lt: 18 } },
353
{ $set: { status: 'minor' } }
354
);
355
356
// Find and update with return
357
const updatedUser = await User.findOneAndUpdate(
358
{ email: 'john@example.com' },
359
{ $inc: { loginCount: 1 } },
360
{ new: true } // Return updated document
361
);
362
363
// Update by ID
364
const user = await User.findByIdAndUpdate(
365
userId,
366
{ lastLogin: new Date() },
367
{ new: true }
368
);
369
370
// Upsert (update or insert)
371
const user = await User.findOneAndUpdate(
372
{ email: 'new@example.com' },
373
{ name: 'New User', age: 25 },
374
{ upsert: true, new: true }
375
);
376
```
377
378
### Delete Operations
379
380
Remove documents from the database.
381
382
```javascript { .api }
383
interface Model<T> {
384
/**
385
* Delete single document
386
* @param filter - Query conditions
387
* @param options - Delete options
388
* @returns Promise resolving to delete result
389
*/
390
static deleteOne<T>(
391
filter: FilterQuery<T>,
392
options?: DeleteOptions
393
): Promise<DeleteResult>;
394
395
/**
396
* Delete multiple documents
397
* @param filter - Query conditions
398
* @param options - Delete options
399
* @returns Promise resolving to delete result
400
*/
401
static deleteMany<T>(
402
filter: FilterQuery<T>,
403
options?: DeleteOptions
404
): Promise<DeleteResult>;
405
406
/**
407
* Find and delete single document
408
* @param filter - Query conditions
409
* @param options - Delete options
410
* @returns Promise resolving to deleted document
411
*/
412
static findOneAndDelete<T>(
413
filter: FilterQuery<T>,
414
options?: FindOneAndDeleteOptions
415
): Promise<T | null>;
416
417
/**
418
* Find by ID and delete
419
* @param id - Document ID
420
* @param options - Delete options
421
* @returns Promise resolving to deleted document
422
*/
423
static findByIdAndDelete<T>(
424
id: any,
425
options?: FindOneAndDeleteOptions
426
): Promise<T | null>;
427
428
/**
429
* Remove documents (deprecated, use deleteOne/deleteMany)
430
* @param filter - Query conditions
431
* @returns Promise resolving to delete result
432
*/
433
static remove<T>(filter: FilterQuery<T>): Promise<any>;
434
}
435
436
interface DeleteOptions {
437
/** Write concern */
438
writeConcern?: any;
439
440
/** Collation */
441
collation?: any;
442
}
443
444
interface FindOneAndDeleteOptions extends DeleteOptions {
445
/** Fields to return */
446
select?: string | object;
447
448
/** Sort order */
449
sort?: string | object;
450
451
/** Maximum time to wait */
452
maxTimeMS?: number;
453
}
454
```
455
456
**Usage Examples:**
457
458
```javascript
459
// Delete single document
460
const result = await User.deleteOne({ email: 'john@example.com' });
461
console.log(result.deletedCount); // 1
462
463
// Delete multiple documents
464
await User.deleteMany({ age: { $lt: 18 } });
465
466
// Find and delete with return
467
const deletedUser = await User.findOneAndDelete({
468
email: 'john@example.com'
469
});
470
471
// Delete by ID
472
const deletedUser = await User.findByIdAndDelete(userId);
473
474
// Check deletion result
475
if (result.deletedCount > 0) {
476
console.log('Document deleted successfully');
477
}
478
```
479
480
### Bulk Operations
481
482
Perform multiple operations in a single database round trip.
483
484
```javascript { .api }
485
interface Model<T> {
486
/**
487
* Execute bulk write operations
488
* @param operations - Array of bulk operations
489
* @param options - Bulk options
490
* @returns Promise resolving to bulk result
491
*/
492
static bulkWrite<T>(
493
operations: BulkWriteOperation<T>[],
494
options?: BulkWriteOptions
495
): Promise<BulkWriteResult>;
496
497
/**
498
* Save multiple documents with validation
499
* @param documents - Array of documents to save
500
* @param options - Save options
501
* @returns Promise resolving to saved documents
502
*/
503
static bulkSave<T>(
504
documents: T[],
505
options?: BulkSaveOptions
506
): Promise<BulkSaveResult>;
507
}
508
509
type BulkWriteOperation<T> =
510
| { insertOne: { document: T } }
511
| { updateOne: { filter: FilterQuery<T>, update: UpdateQuery<T>, upsert?: boolean } }
512
| { updateMany: { filter: FilterQuery<T>, update: UpdateQuery<T>, upsert?: boolean } }
513
| { deleteOne: { filter: FilterQuery<T> } }
514
| { deleteMany: { filter: FilterQuery<T> } }
515
| { replaceOne: { filter: FilterQuery<T>, replacement: T, upsert?: boolean } };
516
517
interface BulkWriteOptions {
518
/** Execute operations in order */
519
ordered?: boolean;
520
521
/** Skip validation */
522
skipValidation?: boolean;
523
524
/** Include write concern */
525
writeConcern?: any;
526
}
527
```
528
529
**Usage Examples:**
530
531
```javascript
532
// Bulk write operations
533
const operations = [
534
{ insertOne: { document: { name: 'Alice', age: 25 } } },
535
{ updateOne: {
536
filter: { name: 'Bob' },
537
update: { $set: { age: 30 } }
538
}},
539
{ deleteOne: { filter: { name: 'Charlie' } } }
540
];
541
542
const result = await User.bulkWrite(operations);
543
console.log(result.insertedCount, result.modifiedCount, result.deletedCount);
544
545
// Bulk save documents
546
const users = [
547
new User({ name: 'Dave', age: 40 }),
548
new User({ name: 'Eve', age: 35 })
549
];
550
551
const saveResult = await User.bulkSave(users);
552
```
553
554
### Aggregation
555
556
Create and execute aggregation pipelines for complex data processing.
557
558
```javascript { .api }
559
interface Model<T> {
560
/**
561
* Create aggregation pipeline
562
* @param pipeline - Aggregation stages
563
* @param options - Aggregation options
564
* @returns Aggregate instance
565
*/
566
static aggregate<T>(
567
pipeline?: PipelineStage[],
568
options?: AggregateOptions
569
): Aggregate<T[]>;
570
}
571
```
572
573
**Usage Examples:**
574
575
```javascript
576
// Basic aggregation
577
const results = await User.aggregate([
578
{ $match: { age: { $gte: 18 } } },
579
{ $group: { _id: '$status', count: { $sum: 1 } } },
580
{ $sort: { count: -1 } }
581
]);
582
583
// Complex aggregation with lookup
584
const userPosts = await User.aggregate([
585
{ $match: { status: 'active' } },
586
{ $lookup: {
587
from: 'posts',
588
localField: '_id',
589
foreignField: 'author',
590
as: 'posts'
591
}},
592
{ $addFields: { postCount: { $size: '$posts' } } },
593
{ $sort: { postCount: -1 } }
594
]);
595
```
596
597
### Index Management
598
599
Manage database indexes for query optimization.
600
601
```javascript { .api }
602
interface Model<T> {
603
/**
604
* Create indexes defined in schema
605
* @param options - Index creation options
606
* @returns Promise resolving when indexes are created
607
*/
608
static createIndexes<T>(options?: any): Promise<void>;
609
610
/**
611
* Synchronize indexes with schema
612
* @param options - Sync options
613
* @returns Promise resolving to sync result
614
*/
615
static syncIndexes<T>(options?: any): Promise<string[]>;
616
617
/**
618
* List all indexes on collection
619
* @returns Promise resolving to index array
620
*/
621
static listIndexes<T>(): Promise<any[]>;
622
623
/**
624
* Ensure index exists
625
* @param fieldOrSpec - Index specification
626
* @param options - Index options
627
* @returns Promise resolving to index name
628
*/
629
static ensureIndexes<T>(options?: any): Promise<void>;
630
}
631
```
632
633
**Usage Examples:**
634
635
```javascript
636
// Create all schema-defined indexes
637
await User.createIndexes();
638
639
// Sync indexes (remove unused, add missing)
640
const result = await User.syncIndexes();
641
console.log('Synced indexes:', result);
642
643
// List existing indexes
644
const indexes = await User.listIndexes();
645
console.log('Current indexes:', indexes);
646
```
647
648
### Additional Model Methods
649
650
Advanced model operations for index management, collection operations, and database administration.
651
652
```javascript { .api }
653
interface Model<T> {
654
/**
655
* Create aggregation pipeline
656
* @param pipeline - Array of aggregation stages
657
* @returns Aggregate instance
658
*/
659
static aggregate<ResultType>(pipeline?: PipelineStage[]): Aggregate<ResultType[]>;
660
661
/**
662
* Explicitly create collection in database
663
* @param options - Collection creation options
664
* @returns Promise resolving to native collection
665
*/
666
static createCollection(options?: CreateCollectionOptions): Promise<mongodb.Collection>;
667
668
/**
669
* Create all schema indexes
670
* @param options - Index creation options
671
* @returns Promise that resolves when indexes are created
672
*/
673
static createIndexes(options?: any): Promise<void>;
674
675
/**
676
* Compare schema indexes with database indexes
677
* @returns Promise with index differences
678
*/
679
static diffIndexes(): Promise<IndexesDiff>;
680
681
/**
682
* Deprecated alias for createIndexes
683
* @returns Promise that resolves when indexes are created
684
*/
685
static ensureIndexes(): Promise<void>;
686
687
/**
688
* Create document from plain object without validation
689
* @param obj - Plain object to hydrate
690
* @param projection - Field projection
691
* @returns Hydrated document instance
692
*/
693
static hydrate(obj: any, projection?: any): HydratedDocument<T>;
694
695
/**
696
* Initialize model (create collection and indexes)
697
* @returns Promise resolving to model
698
*/
699
static init(): Promise<Model<T>>;
700
701
/**
702
* List all indexes for this model's collection
703
* @returns Promise with array of index definitions
704
*/
705
static listIndexes(): Promise<IndexDefinition[]>;
706
707
/**
708
* Start database session for transactions
709
* @param options - Session options
710
* @returns Promise with client session
711
*/
712
static startSession(options?: ClientSessionOptions): Promise<ClientSession>;
713
714
/**
715
* Synchronize schema indexes with database
716
* @param options - Sync options
717
* @returns Promise with array of synced index names
718
*/
719
static syncIndexes(options?: SyncIndexesOptions): Promise<string[]>;
720
721
/**
722
* Translate field aliases in query object
723
* @param raw - Raw query object
724
* @returns Query object with translated aliases
725
*/
726
static translateAliases(raw: any): any;
727
728
/**
729
* Validate object against schema without creating document
730
* @param obj - Object to validate
731
* @param pathsToValidate - Specific paths to validate
732
* @returns Promise that resolves if valid, rejects if invalid
733
*/
734
static validate(obj: any, pathsToValidate?: string[]): Promise<void>;
735
736
/**
737
* Create change stream on collection
738
* @param pipeline - Aggregation pipeline for filtering changes
739
* @param options - Change stream options
740
* @returns Change stream cursor
741
*/
742
static watch(pipeline?: any[], options?: ChangeStreamOptions): ChangeStream;
743
}
744
```
745
746
## Types
747
748
```javascript { .api }
749
interface UpdateResult {
750
/** Operation was accepted */
751
acknowledged: boolean;
752
753
/** Number of documents matched */
754
matchedCount: number;
755
756
/** Number of documents modified */
757
modifiedCount: number;
758
759
/** ID of upserted document */
760
upsertedId?: ObjectId;
761
762
/** Number of documents upserted */
763
upsertedCount: number;
764
}
765
766
interface DeleteResult {
767
/** Operation was accepted */
768
acknowledged: boolean;
769
770
/** Number of documents deleted */
771
deletedCount: number;
772
}
773
774
interface BulkWriteResult {
775
/** Operation was accepted */
776
acknowledged: boolean;
777
778
/** Number of documents inserted */
779
insertedCount: number;
780
781
/** IDs of inserted documents */
782
insertedIds: { [index: number]: ObjectId };
783
784
/** Number of documents matched */
785
matchedCount: number;
786
787
/** Number of documents modified */
788
modifiedCount: number;
789
790
/** Number of documents deleted */
791
deletedCount: number;
792
793
/** Number of documents upserted */
794
upsertedCount: number;
795
796
/** IDs of upserted documents */
797
upsertedIds: { [index: number]: ObjectId };
798
}
799
800
type FilterQuery<T> = {
801
[P in keyof T]?: T[P] | QuerySelector<T[P]>;
802
} & QuerySelector<T>;
803
804
interface QuerySelector<T> {
805
$eq?: T;
806
$ne?: T;
807
$gt?: T;
808
$gte?: T;
809
$lt?: T;
810
$lte?: T;
811
$in?: T[];
812
$nin?: T[];
813
$exists?: boolean;
814
$regex?: RegExp | string;
815
$options?: string;
816
$all?: T[];
817
$size?: number;
818
$elemMatch?: any;
819
$not?: QuerySelector<T>;
820
$and?: FilterQuery<T>[];
821
$or?: FilterQuery<T>[];
822
$nor?: FilterQuery<T>[];
823
$where?: string | Function;
824
$expr?: any;
825
$jsonSchema?: any;
826
$mod?: [number, number];
827
$text?: {
828
$search: string;
829
$language?: string;
830
$caseSensitive?: boolean;
831
$diacriticSensitive?: boolean;
832
};
833
$near?: any;
834
$nearSphere?: any;
835
$geoIntersects?: any;
836
$geoWithin?: any;
837
$within?: any;
838
$centerSphere?: any;
839
}
840
841
type UpdateQuery<T> = {
842
$set?: Partial<T>;
843
$unset?: { [K in keyof T]?: '' | 1 | true };
844
$inc?: Partial<T>;
845
$mul?: Partial<T>;
846
$min?: Partial<T>;
847
$max?: Partial<T>;
848
$push?: any;
849
$pushAll?: any;
850
$addToSet?: any;
851
$pop?: any;
852
$pull?: any;
853
$pullAll?: any;
854
$rename?: { [key: string]: string };
855
$bit?: any;
856
$currentDate?: any;
857
} & Partial<T>;
858
859
type ProjectionType<T> = string | { [K in keyof T]?: 1 | 0 | boolean } | { [key: string]: 1 | 0 | boolean };
860
861
interface CreateCollectionOptions {
862
/** Capped collection options */
863
capped?: boolean;
864
865
/** Maximum collection size */
866
size?: number;
867
868
/** Maximum document count */
869
max?: number;
870
871
/** Validation rules */
872
validator?: any;
873
874
/** Validation level */
875
validationLevel?: 'off' | 'strict' | 'moderate';
876
877
/** Validation action */
878
validationAction?: 'error' | 'warn';
879
}
880
881
interface IndexesDiff {
882
/** Indexes to create */
883
toDrop: IndexDefinition[];
884
885
/** Indexes to drop */
886
toCreate: IndexDefinition[];
887
}
888
889
interface IndexDefinition {
890
/** Index specification */
891
key: any;
892
893
/** Index name */
894
name?: string;
895
896
/** Index options */
897
[option: string]: any;
898
}
899
900
interface SyncIndexesOptions {
901
/** Continue on index creation error */
902
continueOnError?: boolean;
903
904
/** Drop indexes not in schema */
905
dropIndexes?: boolean;
906
}
907
908
interface HydratedDocument<T> extends Document {
909
/** Document data */
910
[K in keyof T]: T[K];
911
}
912
913
interface ClientSessionOptions {
914
/** Causally consistent reads */
915
causalConsistency?: boolean;
916
917
/** Default transaction options */
918
defaultTransactionOptions?: TransactionOptions;
919
}
920
921
interface TransactionOptions {
922
/** Read concern */
923
readConcern?: ReadConcern;
924
925
/** Write concern */
926
writeConcern?: WriteConcern;
927
928
/** Read preference */
929
readPreference?: ReadPreference;
930
931
/** Max commit time */
932
maxCommitTimeMS?: number;
933
}
934
935
interface ChangeStreamOptions {
936
/** Full document option */
937
fullDocument?: 'default' | 'updateLookup';
938
939
/** Full document before change */
940
fullDocumentBeforeChange?: 'off' | 'whenAvailable' | 'required';
941
942
/** Resume token */
943
resumeAfter?: any;
944
945
/** Start after token */
946
startAfter?: any;
947
948
/** Start at operation time */
949
startAtOperationTime?: any;
950
951
/** Max await time */
952
maxAwaitTimeMS?: number;
953
954
/** Batch size */
955
batchSize?: number;
956
957
/** Collation */
958
collation?: any;
959
}
960
961
interface ChangeStream {
962
/** Stream next change */
963
next(): Promise<ChangeStreamDocument>;
964
965
/** Close stream */
966
close(): Promise<void>;
967
968
/** Check if stream is closed */
969
isClosed(): boolean;
970
971
/** Resume token */
972
resumeToken: any;
973
}
974
975
interface ChangeStreamDocument {
976
/** Operation type */
977
operationType: 'insert' | 'update' | 'replace' | 'delete' | 'invalidate' | 'drop' | 'dropDatabase' | 'rename';
978
979
/** Full document */
980
fullDocument?: any;
981
982
/** Document key */
983
documentKey?: any;
984
985
/** Update description */
986
updateDescription?: {
987
updatedFields?: any;
988
removedFields?: string[];
989
};
990
991
/** Resume token */
992
_id: any;
993
994
/** Namespace */
995
ns: {
996
db: string;
997
coll: string;
998
};
999
1000
/** Cluster time */
1001
clusterTime: any;
1002
}
1003
```