forked from 418sec/mongoose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.d.ts
2734 lines (2200 loc) · 119 KB
/
index.d.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
declare module 'mongoose' {
import events = require('events');
import mongodb = require('mongodb');
import mongoose = require('mongoose');
import stream = require('stream');
export enum ConnectionStates {
disconnected = 0,
connected = 1,
connecting = 2,
disconnecting = 3,
uninitialized = 99,
}
/** The Mongoose Date [SchemaType](/docs/schematypes.html). */
export type Date = Schema.Types.Date;
/**
* The Mongoose Decimal128 [SchemaType](/docs/schematypes.html). Used for
* declaring paths in your schema that should be
* [128-bit decimal floating points](http://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-decimal.html).
* Do not use this to create a new Decimal128 instance, use `mongoose.Types.Decimal128`
* instead.
*/
export type Decimal128 = Schema.Types.Decimal128;
/**
* The Mongoose Mixed [SchemaType](/docs/schematypes.html). Used for
* declaring paths in your schema that Mongoose's change tracking, casting,
* and validation should ignore.
*/
export type Mixed = Schema.Types.Mixed;
/**
* Mongoose constructor. The exports object of the `mongoose` module is an instance of this
* class. Most apps will only use this one instance.
*/
// eslint-disable-next-line @typescript-eslint/ban-types
export const Mongoose: new (options?: object | null) => typeof mongoose;
/**
* The Mongoose Number [SchemaType](/docs/schematypes.html). Used for
* declaring paths in your schema that Mongoose should cast to numbers.
*/
export type Number = Schema.Types.Number;
/**
* The Mongoose ObjectId [SchemaType](/docs/schematypes.html). Used for
* declaring paths in your schema that should be
* [MongoDB ObjectIds](https://docs.mongodb.com/manual/reference/method/ObjectId/).
* Do not use this to create a new ObjectId instance, use `mongoose.Types.ObjectId`
* instead.
*/
export type ObjectId = Schema.Types.ObjectId;
export let Promise: any;
export const PromiseProvider: any;
/** The various Mongoose SchemaTypes. */
export const SchemaTypes: typeof Schema.Types;
/** Expose connection states for user-land */
export const STATES: typeof ConnectionStates;
/** Opens Mongoose's default connection to MongoDB, see [connections docs](https://mongoosejs.com/docs/connections.html) */
export function connect(uri: string, options: ConnectOptions, callback: (err: CallbackError) => void): void;
export function connect(uri: string, callback: (err: CallbackError) => void): void;
export function connect(uri: string, options?: ConnectOptions): Promise<Mongoose>;
/** The Mongoose module's default connection. Equivalent to `mongoose.connections[0]`, see [`connections`](#mongoose_Mongoose-connections). */
export const connection: Connection;
/** An array containing all connections associated with this Mongoose instance. */
export const connections: Connection[];
/** An array containing all models associated with this Mongoose instance. */
export const models: { [index: string]: Model<any> };
/** Creates a Connection instance. */
export function createConnection(uri: string, options?: ConnectOptions): Connection & Promise<Connection>;
export function createConnection(): Connection;
export function createConnection(uri: string, options: ConnectOptions, callback: (err: CallbackError, conn: Connection) => void): void;
/**
* Removes the model named `name` from the default connection, if it exists.
* You can use this function to clean up any models you created in your tests to
* prevent OverwriteModelErrors.
*/
export function deleteModel(name: string | RegExp): typeof mongoose;
export function disconnect(): Promise<void>;
export function disconnect(cb: (err: CallbackError) => void): void;
/** Gets mongoose options */
export function get(key: string): any;
/**
* Returns true if Mongoose can cast the given value to an ObjectId, or
* false otherwise.
*/
export function isValidObjectId(v: any): boolean;
export function model<T extends Document>(name: string, schema?: Schema<any>, collection?: string, skipInit?: boolean): Model<T>;
export function model<T extends Document, U extends Model<T, TQueryHelpers>, TQueryHelpers = {}>(
name: string,
schema?: Schema<T, U>,
collection?: string,
skipInit?: boolean
): U;
/** Returns an array of model names created on this instance of Mongoose. */
export function modelNames(): Array<string>;
/** The node-mongodb-native driver Mongoose uses. */
export const mongo: typeof mongodb;
/**
* Mongoose uses this function to get the current time when setting
* [timestamps](/docs/guide.html#timestamps). You may stub out this function
* using a tool like [Sinon](https://www.npmjs.com/package/sinon) for testing.
*/
export function now(): Date;
/** Declares a global plugin executed on all Schemas. */
export function plugin(fn: (schema: Schema, opts?: any) => void, opts?: any): typeof mongoose;
/** Getter/setter around function for pluralizing collection names. */
export function pluralize(fn?: (str: string) => string): (str: string) => string;
/** Sets mongoose options */
export function set(key: string, value: any): void;
/**
* _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions)
* for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/),
* and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
*/
export function startSession(options?: mongodb.SessionOptions): Promise<mongodb.ClientSession>;
export function startSession(options: mongodb.SessionOptions, cb: (err: any, session: mongodb.ClientSession) => void): void;
/** The Mongoose version */
export const version: string;
export type CastError = Error.CastError;
type Mongoose = typeof mongoose;
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface ClientSession extends mongodb.ClientSession { }
interface ConnectOptions extends mongodb.MongoClientOptions {
/** Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. */
bufferCommands?: boolean;
/** The name of the database you want to use. If not provided, Mongoose uses the database name from connection string. */
dbName?: string;
/** username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. */
user?: string;
/** password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. */
pass?: string;
/** Set to false to disable automatic index creation for all models associated with this connection. */
autoIndex?: boolean;
/** True by default. Set to `false` to make `findOneAndUpdate()` and `findOneAndRemove()` use native `findOneAndUpdate()` rather than `findAndModify()`. */
useFindAndModify?: boolean;
/** Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection. */
autoCreate?: boolean;
/** False by default. If `true`, this connection will use `createIndex()` instead of `ensureIndex()` for automatic index builds via `Model.init()`. */
useCreateIndex?: boolean;
}
class Connection extends events.EventEmitter {
/** Closes the connection */
close(callback: (err: CallbackError) => void): void;
close(force: boolean, callback: (err: CallbackError) => void): void;
close(force?: boolean): Promise<void>;
/** Retrieves a collection, creating it if not cached. */
collection(name: string, options?: mongodb.CollectionCreateOptions): Collection;
/** A hash of the collections associated with this connection */
collections: { [index: string]: Collection };
/** A hash of the global options that are associated with this connection */
config: any;
/** The mongodb.Db instance, set when the connection is opened */
db: mongodb.Db;
/**
* Helper for `createCollection()`. Will explicitly create the given collection
* with specified options. Used to create [capped collections](https://docs.mongodb.com/manual/core/capped-collections/)
* and [views](https://docs.mongodb.com/manual/core/views/) from mongoose.
*/
createCollection<T = any>(name: string, options?: mongodb.CollectionCreateOptions): Promise<mongodb.Collection<T>>;
createCollection<T = any>(name: string, cb: (err: CallbackError, collection: mongodb.Collection<T>) => void): void;
createCollection<T = any>(name: string, options: mongodb.CollectionCreateOptions, cb?: (err: CallbackError, collection: mongodb.Collection) => void): Promise<mongodb.Collection<T>>;
/**
* Removes the model named `name` from this connection, if it exists. You can
* use this function to clean up any models you created in your tests to
* prevent OverwriteModelErrors.
*/
deleteModel(name: string): this;
/**
* Helper for `dropCollection()`. Will delete the given collection, including
* all documents and indexes.
*/
dropCollection(collection: string): Promise<void>;
dropCollection(collection: string, cb: (err: CallbackError) => void): void;
/**
* Helper for `dropDatabase()`. Deletes the given database, including all
* collections, documents, and indexes.
*/
dropDatabase(): Promise<void>;
dropDatabase(cb: (err: CallbackError) => void): void;
/** Gets the value of the option `key`. Equivalent to `conn.options[key]` */
get(key: string): any;
/**
* Returns the [MongoDB driver `MongoClient`](http://mongodb.github.io/node-mongodb-native/3.5/api/MongoClient.html) instance
* that this connection uses to talk to MongoDB.
*/
getClient(): mongodb.MongoClient;
/**
* The host name portion of the URI. If multiple hosts, such as a replica set,
* this will contain the first host name in the URI
*/
host: string;
/**
* A number identifier for this connection. Used for debugging when
* you have [multiple connections](/docs/connections.html#multiple_connections).
*/
id: number;
/**
* A [POJO](https://masteringjs.io/tutorials/fundamentals/pojo) containing
* a map from model names to models. Contains all models that have been
* added to this connection using [`Connection#model()`](/docs/api/connection.html#connection_Connection-model).
*/
models: { [index: string]: Model<any> };
/** Defines or retrieves a model. */
model<T extends Document>(name: string, schema?: Schema<T>, collection?: string): Model<T>;
model<T extends Document, U extends Model<T, TQueryHelpers>, TQueryHelpers = {}>(
name: string,
schema?: Schema<T, U, TQueryHelpers>,
collection?: string,
skipInit?: boolean
): U;
/** Returns an array of model names created on this connection. */
modelNames(): Array<string>;
/** The name of the database this connection points to. */
name: string;
/** Opens the connection with a URI using `MongoClient.connect()`. */
openUri(uri: string, options?: ConnectOptions): Promise<Connection>;
openUri(uri: string, callback: (err: CallbackError, conn?: Connection) => void): Connection;
openUri(uri: string, options: ConnectOptions, callback: (err: CallbackError, conn?: Connection) => void): Connection;
/** The password specified in the URI */
pass: string;
/**
* The port portion of the URI. If multiple hosts, such as a replica set,
* this will contain the port from the first host name in the URI.
*/
port: number;
/** Declares a plugin executed on all schemas you pass to `conn.model()` */
plugin(fn: (schema: Schema, opts?: any) => void, opts?: any): Connection;
/** The plugins that will be applied to all models created on this connection. */
plugins: Array<any>;
/**
* Connection ready state
*
* - 0 = disconnected
* - 1 = connected
* - 2 = connecting
* - 3 = disconnecting
*/
readyState: number;
/** Sets the value of the option `key`. Equivalent to `conn.options[key] = val` */
set(key: string, value: any): any;
/**
* Set the [MongoDB driver `MongoClient`](http://mongodb.github.io/node-mongodb-native/3.5/api/MongoClient.html) instance
* that this connection uses to talk to MongoDB. This is useful if you already have a MongoClient instance, and want to
* reuse it.
*/
setClient(client: mongodb.MongoClient): this;
/**
* _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions)
* for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/),
* and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
*/
startSession(options?: mongodb.SessionOptions): Promise<mongodb.ClientSession>;
startSession(options: mongodb.SessionOptions, cb: (err: any, session: mongodb.ClientSession) => void): void;
/**
* _Requires MongoDB >= 3.6.0._ Executes the wrapped async function
* in a transaction. Mongoose will commit the transaction if the
* async function executes successfully and attempt to retry if
* there was a retriable error.
*/
transaction(fn: (session: mongodb.ClientSession) => Promise<any>): Promise<any>;
/** Switches to a different database using the same connection pool. */
useDb(name: string, options?: { useCache?: boolean, noListener?: boolean }): Connection;
/** The username specified in the URI */
user: string;
/** Watches the entire underlying database for changes. Similar to [`Model.watch()`](/docs/api/model.html#model_Model.watch). */
watch(pipeline?: Array<any>, options?: mongodb.ChangeStreamOptions): mongodb.ChangeStream;
}
/*
* section collection.js
* http://mongoosejs.com/docs/api.html#collection-js
*/
interface CollectionBase extends mongodb.Collection {
/*
* Abstract methods. Some of these are already defined on the
* mongodb.Collection interface so they've been commented out.
*/
ensureIndex(...args: any[]): any;
findAndModify(...args: any[]): any;
getIndexes(...args: any[]): any;
/** The collection name */
collectionName: string;
/** The Connection instance */
conn: Connection;
/** The collection name */
name: string;
}
/*
* section drivers/node-mongodb-native/collection.js
* http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-collection-js
*/
let Collection: Collection;
interface Collection extends CollectionBase {
/**
* Collection constructor
* @param name name of the collection
* @param conn A MongooseConnection instance
* @param opts optional collection options
*/
// eslint-disable-next-line @typescript-eslint/no-misused-new
new(name: string, conn: Connection, opts?: any): Collection;
/** Formatter for debug print args */
$format(arg: any): string;
/** Debug print helper */
$print(name: any, i: any, args: any[]): void;
/** Retrieves information about this collections indexes. */
getIndexes(): any;
}
class Document<T = any, TQueryHelpers = {}> {
constructor(doc?: any);
/** This documents _id. */
_id?: T;
/** This documents __v. */
__v?: number;
/* Get all subdocs (by bfs) */
$getAllSubdocs(): Document[];
/** Don't run validation on this path or persist changes to this path. */
$ignore(path: string): void;
/** Checks if a path is set to its default. */
$isDefault(path: string): boolean;
/** Getter/setter, determines whether the document was removed or not. */
$isDeleted(val?: boolean): boolean;
/** Returns an array of all populated documents associated with the query */
$getPopulatedDocs(): Document[];
/**
* Returns true if the given path is nullish or only contains empty objects.
* Useful for determining whether this subdoc will get stripped out by the
* [minimize option](/docs/guide.html#minimize).
*/
$isEmpty(path: string): boolean;
/** Checks if a path is invalid */
$isValid(path: string): boolean;
/**
* Empty object that you can use for storing properties on the document. This
* is handy for passing data to middleware without conflicting with Mongoose
* internals.
*/
$locals: Record<string, unknown>;
/** Marks a path as valid, removing existing validation errors. */
$markValid(path: string): void;
/**
* A string containing the current operation that Mongoose is executing
* on this document. May be `null`, `'save'`, `'validate'`, or `'remove'`.
*/
$op: string | null;
/**
* Getter/setter around the session associated with this document. Used to
* automatically set `session` if you `save()` a doc that you got from a
* query with an associated session.
*/
$session(session?: mongodb.ClientSession | null): mongodb.ClientSession;
/** Alias for `set()`, used internally to avoid conflicts */
$set(path: string, val: any, options?: any): this;
$set(path: string, val: any, type: any, options?: any): this;
$set(value: any): this;
/** Additional properties to attach to the query when calling `save()` and `isNew` is false. */
$where: Record<string, unknown>;
/** If this is a discriminator model, `baseModelName` is the name of the base model. */
baseModelName?: string;
/** Collection the model uses. */
collection: Collection;
/** Connection the model uses. */
db: Connection;
/** Removes this document from the db. */
delete(options?: QueryOptions): QueryWithHelpers<any, this, TQueryHelpers>;
delete(options?: QueryOptions, cb?: (err: CallbackError, res: any) => void): void;
/** Removes this document from the db. */
deleteOne(options?: QueryOptions): QueryWithHelpers<any, this, TQueryHelpers>;
deleteOne(options?: QueryOptions, cb?: (err: CallbackError, res: any) => void): void;
/** Takes a populated field and returns it to its unpopulated state. */
depopulate(path: string): this;
/**
* Returns the list of paths that have been directly modified. A direct
* modified path is a path that you explicitly set, whether via `doc.foo = 'bar'`,
* `Object.assign(doc, { foo: 'bar' })`, or `doc.set('foo', 'bar')`.
*/
directModifiedPaths(): Array<string>;
/**
* Returns true if this document is equal to another document.
*
* Documents are considered equal when they have matching `_id`s, unless neither
* document has an `_id`, in which case this function falls back to using
* `deepEqual()`.
*/
equals(doc: Document<T>): boolean;
/** Hash containing current validation errors. */
errors?: Error.ValidationError;
/** Explicitly executes population and returns a promise. Useful for promises integration. */
execPopulate(): Promise<this>;
execPopulate(callback: (err: CallbackError, res: this) => void): void;
/** Returns the value of a path. */
get(path: string, type?: any, options?: any): any;
/**
* Returns the changes that happened to the document
* in the format that will be sent to MongoDB.
*/
getChanges(): UpdateQuery<this>;
/** The string version of this documents _id. */
id?: any;
/** Signal that we desire an increment of this documents version. */
increment(): this;
/**
* Initializes the document without setters or marking anything modified.
* Called internally after a document is returned from mongodb. Normally,
* you do **not** need to call this function on your own.
*/
init(obj: any, opts?: any, cb?: (err: CallbackError, doc: this) => void): this;
/** Marks a path as invalid, causing validation to fail. */
invalidate(path: string, errorMsg: string | NativeError, value?: any, kind?: string): NativeError | null;
/** Returns true if `path` was directly set and modified, else false. */
isDirectModified(path: string): boolean;
/** Checks if `path` was explicitly selected. If no projection, always returns true. */
isDirectSelected(path: string): boolean;
/** Checks if `path` is in the `init` state, that is, it was set by `Document#init()` and not modified since. */
isInit(path: string): boolean;
/**
* Returns true if any of the given paths is modified, else false. If no arguments, returns `true` if any path
* in this document is modified.
*/
isModified(path?: string | Array<string>): boolean;
/** Boolean flag specifying if the document is new. */
isNew: boolean;
/** Checks if `path` was selected in the source query which initialized this document. */
isSelected(path: string): boolean;
/** Marks the path as having pending changes to write to the db. */
markModified(path: string, scope?: any): void;
/** Returns the list of paths that have been modified. */
modifiedPaths(options?: { includeChildren?: boolean }): Array<string>;
/** Returns another Model instance. */
model<T extends Model<any>>(name: string): T;
/** The name of the model */
modelName: string;
/**
* Overwrite all values in this document with the values of `obj`, except
* for immutable properties. Behaves similarly to `set()`, except for it
* unsets all properties that aren't in `obj`.
*/
overwrite(obj: DocumentDefinition<this>): this;
/**
* Populates document references, executing the `callback` when complete.
* If you want to use promises instead, use this function with
* [`execPopulate()`](#document_Document-execPopulate).
*/
populate(path: string, callback?: (err: CallbackError, res: this) => void): this;
populate(path: string, names: string, callback?: (err: any, res: this) => void): this;
populate(opts: PopulateOptions | Array<PopulateOptions>, callback?: (err: CallbackError, res: this) => void): this;
/** Gets _id(s) used during population of the given `path`. If the path was not populated, returns `undefined`. */
populated(path: string): any;
/** Removes this document from the db. */
remove(options?: QueryOptions): Promise<this>;
remove(options?: QueryOptions, cb?: (err: CallbackError, res: any) => void): void;
/** Sends a replaceOne command with this document `_id` as the query selector. */
replaceOne(replacement?: DocumentDefinition<this>, options?: QueryOptions | null, callback?: (err: any, res: any) => void): Query<any, this>;
/** Saves this document by inserting a new document into the database if [document.isNew](/docs/api.html#document_Document-isNew) is `true`, or sends an [updateOne](/docs/api.html#document_Document-updateOne) operation with just the modified paths if `isNew` is `false`. */
save(options?: SaveOptions): Promise<this>;
save(options?: SaveOptions, fn?: (err: CallbackError, doc: this) => void): void;
save(fn?: (err: CallbackError, doc: this) => void): void;
/** The document's schema. */
schema: Schema;
/** Sets the value of a path, or many paths. */
set(path: string, val: any, options?: any): this;
set(path: string, val: any, type: any, options?: any): this;
set(value: any): this;
/** The return value of this method is used in calls to JSON.stringify(doc). */
toJSON(options?: ToObjectOptions): LeanDocument<this>;
toJSON<T>(options?: ToObjectOptions): T;
/** Converts this document into a plain-old JavaScript object ([POJO](https://masteringjs.io/tutorials/fundamentals/pojo)). */
toObject(options?: ToObjectOptions): LeanDocument<this>;
toObject<T>(options?: ToObjectOptions): T;
/** Clears the modified state on the specified path. */
unmarkModified(path: string): void;
/** Sends an update command with this document `_id` as the query selector. */
update(update?: UpdateQuery<this>, options?: QueryOptions | null, callback?: (err: CallbackError, res: any) => void): Query<any, this>;
/** Sends an updateOne command with this document `_id` as the query selector. */
updateOne(update?: UpdateQuery<this>, options?: QueryOptions | null, callback?: (err: CallbackError, res: any) => void): Query<any, this>;
/** Executes registered validation rules for this document. */
validate(pathsToValidate?: Array<string>, options?: any): Promise<void>;
validate(callback: (err: CallbackError) => void): void;
validate(pathsToValidate: Array<string>, callback: (err: CallbackError) => void): void;
validate(pathsToValidate: Array<string>, options: any, callback: (err: CallbackError) => void): void;
/** Executes registered validation rules (skipping asynchronous validators) for this document. */
validateSync(pathsToValidate?: Array<string>, options?: any): NativeError | null;
}
export const Model: Model<any>;
// eslint-disable-next-line no-undef
interface Model<T extends Document, TQueryHelpers = {}> extends NodeJS.EventEmitter {
new(doc?: any): T;
aggregate<R = any>(pipeline?: any[]): Aggregate<Array<R>>;
// eslint-disable-next-line @typescript-eslint/ban-types
aggregate<R = any>(pipeline: any[], cb: Function): Promise<Array<R>>;
/** Base Mongoose instance the model uses. */
base: typeof mongoose;
/**
* If this is a discriminator model, `baseModelName` is the name of
* the base model.
*/
baseModelName: string | undefined;
/**
* Sends multiple `insertOne`, `updateOne`, `updateMany`, `replaceOne`,
* `deleteOne`, and/or `deleteMany` operations to the MongoDB server in one
* command. This is faster than sending multiple independent operations (e.g.
* if you use `create()`) because with `bulkWrite()` there is only one round
* trip to MongoDB.
*/
bulkWrite(writes: Array<any>, options?: mongodb.CollectionBulkWriteOptions): Promise<mongodb.BulkWriteOpResultObject>;
bulkWrite(writes: Array<any>, options?: mongodb.CollectionBulkWriteOptions, cb?: (err: any, res: mongodb.BulkWriteOpResultObject) => void): void;
/** Collection the model uses. */
collection: Collection;
/** Creates a `count` query: counts the number of documents that match `filter`. */
count(callback?: (err: any, count: number) => void): QueryWithHelpers<number, T, TQueryHelpers>;
count(filter: FilterQuery<T>, callback?: (err: any, count: number) => void): QueryWithHelpers<number, T, TQueryHelpers>;
/** Creates a `countDocuments` query: counts the number of documents that match `filter`. */
countDocuments(callback?: (err: any, count: number) => void): QueryWithHelpers<number, T, TQueryHelpers>;
countDocuments(filter: FilterQuery<T>, callback?: (err: any, count: number) => void): QueryWithHelpers<number, T, TQueryHelpers>;
/** Creates a new document or documents */
create(doc: T | DocumentDefinition<T>): Promise<T>;
create(docs: (T | DocumentDefinition<T>)[], options?: SaveOptions): Promise<T[]>;
create(docs: (T | DocumentDefinition<T>)[], callback: (err: CallbackError, docs: T[]) => void): void;
create(doc: T | DocumentDefinition<T>, callback: (err: CallbackError, doc: T) => void): void;
create<DocContents = T | DocumentDefinition<T>>(docs: DocContents[], options?: SaveOptions): Promise<T[]>;
create<DocContents = T | DocumentDefinition<T>>(doc: DocContents): Promise<T>;
create<DocContents = T | DocumentDefinition<T>>(...docs: DocContents[]): Promise<T[]>;
create<DocContents = T | DocumentDefinition<T>>(docs: DocContents[], callback: (err: CallbackError, docs: T[]) => void): void;
create<DocContents = T | DocumentDefinition<T>>(doc: DocContents, callback: (err: CallbackError, doc: T) => void): void;
/**
* Create the collection for this model. By default, if no indexes are specified,
* mongoose will not create the collection for the model until any documents are
* created. Use this method to create the collection explicitly.
*/
createCollection(options?: mongodb.CollectionCreateOptions): Promise<mongodb.Collection<T>>;
createCollection(options: mongodb.CollectionCreateOptions | null, callback: (err: CallbackError, collection: mongodb.Collection<T>) => void): void;
/**
* Similar to `ensureIndexes()`, except for it uses the [`createIndex`](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#createIndex)
* function.
*/
createIndexes(callback?: (err: any) => void): Promise<void>;
createIndexes(options?: any, callback?: (err: any) => void): Promise<void>;
/** Connection the model uses. */
db: Connection;
/**
* Deletes all of the documents that match `conditions` from the collection.
* Behaves like `remove()`, but deletes all documents that match `conditions`
* regardless of the `single` option.
*/
deleteMany(filter?: FilterQuery<T>, options?: QueryOptions, callback?: (err: CallbackError) => void): QueryWithHelpers<mongodb.DeleteWriteOpResultObject['result'] & { deletedCount?: number }, T, TQueryHelpers>;
/**
* Deletes the first document that matches `conditions` from the collection.
* Behaves like `remove()`, but deletes at most one document regardless of the
* `single` option.
*/
deleteOne(filter?: FilterQuery<T>, options?: QueryOptions, callback?: (err: CallbackError) => void): QueryWithHelpers<mongodb.DeleteWriteOpResultObject['result'] & { deletedCount?: number }, T, TQueryHelpers>;
/**
* Sends `createIndex` commands to mongo for each index declared in the schema.
* The `createIndex` commands are sent in series.
*/
ensureIndexes(callback?: (err: any) => void): Promise<void>;
ensureIndexes(options?: any, callback?: (err: any) => void): Promise<void>;
/**
* Event emitter that reports any errors that occurred. Useful for global error
* handling.
*/
// eslint-disable-next-line no-undef
events: NodeJS.EventEmitter;
/**
* Finds a single document by its _id field. `findById(id)` is almost*
* equivalent to `findOne({ _id: id })`. If you want to query by a document's
* `_id`, use `findById()` instead of `findOne()`.
*/
findById(id: any, projection?: any | null, options?: QueryOptions | null, callback?: (err: CallbackError, doc: T | null) => void): QueryWithHelpers<T | null, T, TQueryHelpers>;
/** Finds one document. */
findOne(filter?: FilterQuery<T>, projection?: any | null, options?: QueryOptions | null, callback?: (err: CallbackError, doc: T | null) => void): QueryWithHelpers<T | null, T, TQueryHelpers>;
/**
* Shortcut for creating a new Document from existing raw data, pre-saved in the DB.
* The document returned has no paths marked as modified initially.
*/
hydrate(obj: any): T;
/**
* This function is responsible for building [indexes](https://docs.mongodb.com/manual/indexes/),
* unless [`autoIndex`](http://mongoosejs.com/docs/guide.html#autoIndex) is turned off.
* Mongoose calls this function automatically when a model is created using
* [`mongoose.model()`](/docs/api.html#mongoose_Mongoose-model) or
* [`connection.model()`](/docs/api.html#connection_Connection-model), so you
* don't need to call it.
*/
init(callback?: (err: any) => void): Promise<T>;
/** Inserts one or more new documents as a single `insertMany` call to the MongoDB server. */
insertMany(doc: T | DocumentDefinition<T>, options: InsertManyOptions & { rawResult: true }): Promise<InsertManyResult>;
insertMany(doc: T | DocumentDefinition<T>, options?: InsertManyOptions): Promise<T>;
insertMany(docs: Array<T | DocumentDefinition<T>>, options: InsertManyOptions & { rawResult: true }): Promise<InsertManyResult>;
insertMany(docs: Array<T | DocumentDefinition<T>>, options?: InsertManyOptions): Promise<Array<T>>;
insertMany(doc: T | DocumentDefinition<T>, options?: InsertManyOptions, callback?: (err: CallbackError, res: T | InsertManyResult) => void): void;
insertMany(docs: Array<T | DocumentDefinition<T>>, options?: InsertManyOptions, callback?: (err: CallbackError, res: Array<T> | InsertManyResult) => void): void;
/**
* Lists the indexes currently defined in MongoDB. This may or may not be
* the same as the indexes defined in your schema depending on whether you
* use the [`autoIndex` option](/docs/guide.html#autoIndex) and if you
* build indexes manually.
*/
listIndexes(callback: (err: CallbackError, res: Array<any>) => void): void;
listIndexes(): Promise<Array<any>>;
/** The name of the model */
modelName: string;
/** Populates document references. */
populate(docs: Array<any>, options: PopulateOptions | Array<PopulateOptions> | string,
callback?: (err: any, res: T[]) => void): Promise<Array<T>>;
populate(doc: any, options: PopulateOptions | Array<PopulateOptions> | string,
callback?: (err: any, res: T) => void): Promise<T>;
/**
* Makes the indexes in MongoDB match the indexes defined in this model's
* schema. This function will drop any indexes that are not defined in
* the model's schema except the `_id` index, and build any indexes that
* are in your schema but not in MongoDB.
*/
syncIndexes(options?: Record<string, unknown>): Promise<Array<string>>;
syncIndexes(options: Record<string, unknown> | null, callback: (err: CallbackError, dropped: Array<string>) => void): void;
/**
* Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions)
* for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/),
* and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
* */
startSession(options?: mongodb.SessionOptions, cb?: (err: any, session: mongodb.ClientSession) => void): Promise<mongodb.ClientSession>;
/** Casts and validates the given object against this model's schema, passing the given `context` to custom validators. */
validate(callback?: (err: any) => void): Promise<void>;
validate(optional: any, callback?: (err: any) => void): Promise<void>;
validate(optional: any, pathsToValidate: string[], callback?: (err: any) => void): Promise<void>;
/** Watches the underlying collection for changes using [MongoDB change streams](https://docs.mongodb.com/manual/changeStreams/). */
watch(pipeline?: Array<Record<string, unknown>>, options?: mongodb.ChangeStreamOptions): mongodb.ChangeStream;
/** Adds a `$where` clause to this query */
// eslint-disable-next-line @typescript-eslint/ban-types
$where(argument: string | Function): QueryWithHelpers<Array<T>, T, TQueryHelpers>;
/** Registered discriminators for this model. */
discriminators: { [name: string]: Model<any> } | undefined;
/** Translate any aliases fields/conditions so the final query or document object is pure */
translateAliases(raw: any): any;
/** Adds a discriminator type. */
discriminator<D extends Document>(name: string, schema: Schema, value?: string): Model<D>;
/** Creates a `distinct` query: returns the distinct values of the given `field` that match `filter`. */
distinct(field: string, filter?: FilterQuery<T>, callback?: (err: any, count: number) => void): QueryWithHelpers<Array<any>, T, TQueryHelpers>;
/** Creates a `estimatedDocumentCount` query: counts the number of documents in the collection. */
estimatedDocumentCount(options?: QueryOptions, callback?: (err: any, count: number) => void): QueryWithHelpers<number, T, TQueryHelpers>;
/**
* Returns true if at least one document exists in the database that matches
* the given `filter`, and false otherwise.
*/
exists(filter: FilterQuery<T>): Promise<boolean>;
exists(filter: FilterQuery<T>, callback: (err: any, res: boolean) => void): void;
/** Creates a `find` query: gets a list of documents that match `filter`. */
find(callback?: (err: any, docs: T[]) => void): QueryWithHelpers<Array<T>, T, TQueryHelpers>;
find(filter: FilterQuery<T>, callback?: (err: any, docs: T[]) => void): QueryWithHelpers<Array<T>, T, TQueryHelpers>;
find(filter: FilterQuery<T>, projection?: any | null, options?: QueryOptions | null, callback?: (err: any, docs: T[]) => void): QueryWithHelpers<Array<T>, T, TQueryHelpers>;
/** Creates a `findByIdAndDelete` query, filtering by the given `_id`. */
findByIdAndDelete(id?: mongodb.ObjectId | any, options?: QueryOptions | null, callback?: (err: any, doc: T | null, res: any) => void): QueryWithHelpers<T | null, T, TQueryHelpers>;
/** Creates a `findByIdAndRemove` query, filtering by the given `_id`. */
findByIdAndRemove(id?: mongodb.ObjectId | any, options?: QueryOptions | null, callback?: (err: any, doc: T | null, res: any) => void): QueryWithHelpers<T | null, T, TQueryHelpers>;
/** Creates a `findOneAndUpdate` query, filtering by the given `_id`. */
findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery<T>, options: QueryOptions & { rawResult: true }, callback?: (err: any, doc: mongodb.FindAndModifyWriteOpResultObject<T>, res: any) => void): QueryWithHelpers<mongodb.FindAndModifyWriteOpResultObject<T>, T, TQueryHelpers>;
findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery<T>, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: any, doc: T, res: any) => void): QueryWithHelpers<T, T, TQueryHelpers>;
findByIdAndUpdate(id?: mongodb.ObjectId | any, update?: UpdateQuery<T>, options?: QueryOptions | null, callback?: (err: any, doc: T | null, res: any) => void): QueryWithHelpers<T | null, T, TQueryHelpers>;
/** Creates a `findOneAndDelete` query: atomically finds the given document, deletes it, and returns the document as it was before deletion. */
findOneAndDelete(filter?: FilterQuery<T>, options?: QueryOptions | null, callback?: (err: any, doc: T | null, res: any) => void): QueryWithHelpers<T | null, T, TQueryHelpers>;
/** Creates a `findOneAndRemove` query: atomically finds the given document and deletes it. */
findOneAndRemove(filter?: FilterQuery<T>, options?: QueryOptions | null, callback?: (err: any, doc: T | null, res: any) => void): QueryWithHelpers<T | null, T, TQueryHelpers>;
/** Creates a `findOneAndReplace` query: atomically finds the given document and replaces it with `replacement`. */
findOneAndReplace(filter: FilterQuery<T>, replacement: DocumentDefinition<T>, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: any, doc: T, res: any) => void): QueryWithHelpers<T, T, TQueryHelpers>;
findOneAndReplace(filter?: FilterQuery<T>, replacement?: DocumentDefinition<T>, options?: QueryOptions | null, callback?: (err: any, doc: T | null, res: any) => void): QueryWithHelpers<T | null, T, TQueryHelpers>;
/** Creates a `findOneAndUpdate` query: atomically find the first document that matches `filter` and apply `update`. */
findOneAndUpdate(filter: FilterQuery<T>, update: UpdateQuery<T>, options: QueryOptions & { rawResult: true }, callback?: (err: any, doc: mongodb.FindAndModifyWriteOpResultObject<T>, res: any) => void): QueryWithHelpers<mongodb.FindAndModifyWriteOpResultObject<T>, T, TQueryHelpers>;
findOneAndUpdate(filter: FilterQuery<T>, update: UpdateQuery<T>, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: any, doc: T, res: any) => void): QueryWithHelpers<T, T, TQueryHelpers>;
findOneAndUpdate(filter?: FilterQuery<T>, update?: UpdateQuery<T>, options?: QueryOptions | null, callback?: (err: any, doc: T | null, res: any) => void): QueryWithHelpers<T | null, T, TQueryHelpers>;
geoSearch(filter?: FilterQuery<T>, options?: GeoSearchOptions, callback?: (err: CallbackError, res: Array<T>) => void): QueryWithHelpers<Array<T>, T, TQueryHelpers>;
/** Executes a mapReduce command. */
mapReduce<Key, Value>(
o: MapReduceOptions<T, Key, Value>,
callback?: (err: any, res: any) => void
): Promise<any>;
remove(filter?: any, callback?: (err: CallbackError) => void): QueryWithHelpers<any, T, TQueryHelpers>;
/** Creates a `replaceOne` query: finds the first document that matches `filter` and replaces it with `replacement`. */
replaceOne(filter?: FilterQuery<T>, replacement?: DocumentDefinition<T>, options?: QueryOptions | null, callback?: (err: any, res: any) => void): QueryWithHelpers<any, T, TQueryHelpers>;
/** Schema the model uses. */
schema: Schema;
/**
* @deprecated use `updateOne` or `updateMany` instead.
* Creates a `update` query: updates one or many documents that match `filter` with `update`, based on the `multi` option.
*/
update(filter?: FilterQuery<T>, update?: UpdateQuery<T>, options?: QueryOptions | null, callback?: (err: any, res: any) => void): QueryWithHelpers<mongodb.WriteOpResult['result'], T, TQueryHelpers>;
/** Creates a `updateMany` query: updates all documents that match `filter` with `update`. */
updateMany(filter?: FilterQuery<T>, update?: UpdateQuery<T>, options?: QueryOptions | null, callback?: (err: any, res: any) => void): QueryWithHelpers<mongodb.UpdateWriteOpResult['result'], T, TQueryHelpers>;
/** Creates a `updateOne` query: updates the first document that matches `filter` with `update`. */
updateOne(filter?: FilterQuery<T>, update?: UpdateQuery<T>, options?: QueryOptions | null, callback?: (err: any, res: any) => void): QueryWithHelpers<mongodb.UpdateWriteOpResult['result'], T, TQueryHelpers>;
/** Creates a Query, applies the passed conditions, and returns the Query. */
where(path: string, val?: any): QueryWithHelpers<Array<T>, T, TQueryHelpers>;
where(obj: object): QueryWithHelpers<Array<T>, T, TQueryHelpers>;
where(): QueryWithHelpers<Array<T>, T, TQueryHelpers>;
}
interface QueryOptions {
arrayFilters?: { [key: string]: any }[];
batchSize?: number;
collation?: mongodb.CollationDocument;
comment?: any;
context?: string;
explain?: any;
fields?: any | string;
hint?: any;
/**
* If truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document.
*/
lean?: boolean | any;
limit?: number;
maxTimeMS?: number;
maxscan?: number;
multi?: boolean;
multipleCastError?: boolean;
/**
* By default, `findOneAndUpdate()` returns the document as it was **before**
* `update` was applied. If you set `new: true`, `findOneAndUpdate()` will
* instead give you the object after `update` was applied.
*/
new?: boolean;
omitUndefined?: boolean;
overwrite?: boolean;
overwriteDiscriminatorKey?: boolean;
populate?: string;
projection?: any;
/**
* if true, returns the raw result from the MongoDB driver
*/
rawResult?: boolean;
readPreference?: mongodb.ReadPreferenceMode;
/**
* An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`.
*/
returnOriginal?: boolean;
runValidators?: boolean;
/** The session associated with this query. */
session?: mongodb.ClientSession;
setDefaultsOnInsert?: boolean;
skip?: number;
snapshot?: any;
sort?: any;
/** overwrites the schema's strict mode option */
strict?: boolean | string;
tailable?: number;
/**
* If set to `false` and schema-level timestamps are enabled,
* skip timestamps for this update. Note that this allows you to overwrite
* timestamps. Does nothing if schema-level timestamps are not set.
*/
timestamps?: boolean;
upsert?: boolean;
useFindAndModify?: boolean;
writeConcern?: any;
}
type MongooseQueryOptions = Pick<QueryOptions, 'populate' | 'lean' | 'omitUndefined' | 'strict' | 'useFindAndModify'>;
interface SaveOptions {
checkKeys?: boolean;
j?: boolean;
safe?: boolean | WriteConcern;
session?: ClientSession | null;
timestamps?: boolean;
validateBeforeSave?: boolean;
validateModifiedOnly?: boolean;
w?: number | string;
wtimeout?: number;
}
interface WriteConcern {
j?: boolean;
w?: number | 'majority' | TagSet;
wtimeout?: number;
}
interface TagSet {
[k: string]: string;
}
interface InsertManyOptions {
limit?: number;
rawResult?: boolean;
ordered?: boolean;
lean?: boolean;
session?: mongodb.ClientSession;
populate?: string | string[] | PopulateOptions | PopulateOptions[];
}
interface InsertManyResult extends mongodb.InsertWriteOpResult<any> {
mongoose?: { validationErrors?: Array<Error.CastError | Error.ValidatorError> }
}
interface MapReduceOptions<T, Key, Val> {
// eslint-disable-next-line @typescript-eslint/ban-types
map: Function | string;
reduce: (key: Key, vals: T[]) => Val;
/** query filter object. */
query?: any;
/** sort input objects using this key */
sort?: any;
/** max number of documents */
limit?: number;
/** keep temporary data default: false */
keeptemp?: boolean;
/** finalize function */
finalize?: (key: Key, val: Val) => Val;
/** scope variables exposed to map/reduce/finalize during execution */
scope?: any;
/** it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X default: false */
jsMode?: boolean;
/** provide statistics on job execution time. default: false */
verbose?: boolean;
readPreference?: string;
/** sets the output target for the map reduce job. default: {inline: 1} */
out?: {
/** the results are returned in an array */
inline?: number;
/**
* {replace: 'collectionName'} add the results to collectionName: the
* results replace the collection
*/
replace?: string;
/**
* {reduce: 'collectionName'} add the results to collectionName: if
* dups are detected, uses the reducer / finalize functions
*/
reduce?: string;
/**
* {merge: 'collectionName'} add the results to collectionName: if
* dups exist the new docs overwrite the old
*/
merge?: string;
};