forked from DefinitelyTyped/DefinitelyTyped
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongoose.d.ts
2521 lines (2205 loc) · 91.2 KB
/
mongoose.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
// Type definitions for Mongoose 4.5.9
// Project: http://mongoosejs.com/
// Definitions by: simonxca <https://github.com/simonxca/>, horiuchi <https://github.com/horiuchi/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
///<reference path="../mongodb/mongodb.d.ts" />
///<reference path="../node/node.d.ts" />
/*
* Guidelines for maintaining these definitions:
* - If you spot an error here or there, please submit a PR.
* Give some examples/links to documentation if you can.
*
* For patches and minor releases:
* - Browse the changelog at https://github.com/Automattic/mongoose/blob/master/History.md
* and make necessary changes. Afterwards, update the version number at the top so we know
* which version we are on.
*
* For major releases:
* - Refer to the updated docs at http://mongoosejs.com/docs/api.html
* - On the left-hand side of the docs is a list of .js files. Reset and update the TODO list below
* then go through one-by-one, making any updates to params list, return type, etc. For documentation
* changes just copy/paste them into here.
* - Check the files off as you go. Some files below might not have anything in them. That's ok, this
* is just a simple heuristic to keep track of our progress.
*
* TODO for version 4.x [updated][tested]:
* [x][x] index.js
* [x][x] querystream.js
* [x][x] connection.js
* [x][x] utils.js
* [x][x] browser.js
* [x][x] drivers/node-mongodb-native/collection.js
* [x][x] drivers/node-mongodb-native/connection.js
* [x][x] error/messages.js
* [x][x] error/validation.js
* [x][x] error.js
* [x][x] querycursor.js
* [x][x] virtualtype.js
* [x][x] schema.js
* [x][x] document.js
* [x][x] types/subdocument.js
* [x][x] types/array.js
* [x][x] types/documentarray.js
* [x][x] types/buffer.js
* [x][x] types/objectid.js
* [x][x] types/embedded.js
* [x][x] query.js
* [x][x] schema/array.js
* [x][x] schema/string.js
* [x][x] schema/documentarray.js
* [x][x] schema/number.js
* [x][x] schema/date.js
* [x][x] schema/buffer.js
* [x][x] schema/boolean.js
* [x][x] schema/objectid.js
* [x][x] schema/mixed.js
* [x][x] schema/embedded.js
* [x][x] aggregate.js
* [x][x] schematype.js
* [x][x] promise.js
* [x][x] ES6Promise.js
* [x][x] model.js
* [x][x] collection.js
*/
/*
For easier searching, add a header to each section like so:
To find a section, CTRL+F and type "section ___.js"
/*
* section filename.js
* http://mongoosejs.com/docs/api.html#filename-js
*/
declare module "mongoose" {
import events = require('events');
import mongodb = require('mongodb');
import stream = require('stream');
import mongoose = require('mongoose');
/*
* Some mongoose classes have the same name as the native JS classes
* Keep references to native classes using a "Native" prefix
*/
class NativeBuffer extends global.Buffer {}
class NativeDate extends global.Date {}
class NativeError extends global.Error {}
/*
* section index.js
* http://mongoosejs.com/docs/api.html#index-js
*/
export var DocumentProvider: any;
// recursive constructor
export var Mongoose: new(...args: any[]) => typeof mongoose;
type Mongoose = typeof mongoose;
export var SchemaTypes: typeof Schema.Types;
/** Expose connection states for user-land */
export var STATES: Object
/** The default connection of the mongoose module. */
export var connection: Connection;
/** The node-mongodb-native driver Mongoose uses. */
export var mongo: typeof mongodb;
/** The Mongoose version */
export var version: string;
/**
* Opens the default mongoose connection.
* Options passed take precedence over options included in connection strings.
* @returns pseudo-promise wrapper around this
*/
export function connect(uris: string,
options?: ConnectionOptions,
callback?: (err: mongodb.MongoError) => void): MongooseThenable;
export function connect(uris: string,
callback?: (err: mongodb.MongoError) => void): MongooseThenable;
/**
* Creates a Connection instance.
* Each connection instance maps to a single database. This method is helpful
* when mangaging multiple db connections.
* @param uri a mongodb:// URI
* @param options options to pass to the driver
* @returns the created Connection object
*/
export function createConnection(): Connection;
export function createConnection(uri: string,
options?: ConnectionOptions
): Connection;
export function createConnection(host: string, database_name: string, port?: number,
options?: ConnectionOptions
): Connection;
/**
* Disconnects all connections.
* @param fn called after all connection close.
* @returns pseudo-promise wrapper around this
*/
export function disconnect(fn?: (error: any) => void): MongooseThenable;
/** Gets mongoose options */
export function get(key: string): any;
/**
* Defines a model or retrieves it.
* Models defined on the mongoose instance are available to all connection
* created by the same mongoose instance.
* @param name model name
* @param collection (optional, induced from model name)
* @param skipInit whether to skip initialization (defaults to false)
*/
export function model<T extends Document>(name: string, schema?: Schema, collection?: string,
skipInit?: boolean): Model<T>;
export function model<T extends Document, U extends Model<T>>(
name: string,
schema?: Schema,
collection?: string,
skipInit?: boolean
): U;
/**
* Returns an array of model names created on this instance of Mongoose.
* Does not include names of models created using connection.model().
*/
export function modelNames(): string[];
/**
* Declares a global plugin executed on all Schemas.
* Equivalent to calling .plugin(fn) on each Schema you create.
* @param fn plugin callback
* @param opts optional options
*/
export function plugin(fn: Function, opts?: Object): typeof mongoose;
/** Sets mongoose options */
export function set(key: string, value: any): void;
type MongooseThenable = typeof mongoose & {
/**
* Ability to use mongoose object as a pseudo-promise so .connect().then()
* and .disconnect().then() are viable.
*/
then<TRes>(onFulfill?: () => void | TRes | PromiseLike<TRes>,
onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike<TRes>): Promise<TRes>;
/**
* Ability to use mongoose object as a pseudo-promise so .connect().then()
* and .disconnect().then() are viable.
*/
catch<TRes>(onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike<TRes>): Promise<TRes>;
}
class CastError extends Error {
/**
* The Mongoose CastError constructor
* @param type The name of the type
* @param value The value that failed to cast
* @param path The path a.b.c in the doc where this cast error occurred
* @param reason The original error that was thrown
*/
constructor(type: string, value: any, path: string, reason?: NativeError);
}
/*
* section querystream.js
* http://mongoosejs.com/docs/api.html#querystream-js
*
* QueryStream can only be accessed using query#stream(), we only
* expose its interface here.
*/
interface QueryStream extends stream.Stream {
/**
* Provides a Node.js 0.8 style ReadStream interface for Queries.
* @event data emits a single Mongoose document
* @event error emits when an error occurs during streaming. This will emit before the close event.
* @event close emits when the stream reaches the end of the cursor or an error occurs, or the stream
* is manually destroyed. After this event, no more events are emitted.
*/
constructor(query: Query<any>, options?: {
/**
* optional function which accepts a mongoose document. The return value
* of the function will be emitted on data.
*/
transform?: Function;
[other: string]: any;
}): QueryStream;
/**
* Destroys the stream, closing the underlying cursor, which emits the close event.
* No more events will be emitted after the close event.
*/
destroy(err?: NativeError): void;
/** Pauses this stream. */
pause(): void;
/** Pipes this query stream into another stream. This method is inherited from NodeJS Streams. */
pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T;
/** Resumes this stream. */
resume(): void;
/** Flag stating whether or not this stream is paused. */
paused: boolean;
/** Flag stating whether or not this stream is readable. */
readable: boolean;
}
/*
* section connection.js
* http://mongoosejs.com/docs/api.html#connection-js
*
* The Connection class exposed by require('mongoose')
* is actually the driver's NativeConnection class.
* connection.js defines a base class that the native
* versions extend. See:
* http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-connection-js
*/
abstract class ConnectionBase extends events.EventEmitter {
/**
* For practical reasons, a Connection equals a Db.
* @param base a mongoose instance
* @event connecting Emitted when connection.{open,openSet}() is executed on this connection.
* @event connected Emitted when this connection successfully connects to the db. May be emitted multiple times in reconnected scenarios.
* @event open Emitted after we connected and onOpen is executed on all of this connections models.
* @event disconnecting Emitted when connection.close() was executed.
* @event disconnected Emitted after getting disconnected from the db.
* @event close Emitted after we disconnected and onClose executed on all of this connections models.
* @event reconnected Emitted after we connected and subsequently disconnected, followed by successfully another successfull connection.
* @event error Emitted when an error occurs on this connection.
* @event fullsetup Emitted in a replica-set scenario, when primary and at least one seconaries specified in the connection string are connected.
* @event all Emitted in a replica-set scenario, when all nodes specified in the connection string are connected.
*/
constructor(base: typeof mongoose);
/**
* Opens the connection to MongoDB.
* @param mongodb://uri or the host to which you are connecting
* @param database database name
* @param port database port
* @param options Mongoose forces the db option forceServerObjectId false and cannot be overridden.
* Mongoose defaults the server auto_reconnect options to true which can be overridden.
* See the node-mongodb-native driver instance for options that it understands.
* Options passed take precedence over options included in connection strings.
*/
open(connection_string: string, database?: string, port?: number,
options?: ConnectionOpenOptions, callback?: (err: any) => void): any;
/**
* Opens the connection to a replica set.
* @param uris comma-separated mongodb:// URIs
* @param database database name if not included in uris
* @param options passed to the internal driver
*/
openSet(uris: string, database?: string, options?: ConnectionOpenSetOptions,
callback?: (err: any) => void): any;
/** Closes the connection */
close(callback?: (err: any) => void): Promise<void>;
/**
* Retrieves a collection, creating it if not cached.
* Not typically needed by applications. Just talk to your collection through your model.
* @param name name of the collection
* @param options optional collection options
*/
collection(name: string, options?: Object): Collection;
/**
* Defines or retrieves a model.
* When no collection argument is passed, Mongoose produces a collection name by passing
* the model name to the utils.toCollectionName method. This method pluralizes the name.
* If you don't like this behavior, either pass a collection name or set your schemas
* collection name option.
* @param name the model name
* @param schema a schema. necessary when defining a model
* @param collection name of mongodb collection (optional) if not given it will be induced from model name
* @returns The compiled model
*/
model<T extends Document>(name: string, schema?: Schema, collection?: string): Model<T>;
model<T extends Document, U extends Model<T>>(
name: string,
schema?: Schema,
collection?: string
): U;
/** Returns an array of model names created on this connection. */
modelNames(): string[];
/** A hash of the global options that are associated with this connection */
config: Object;
/** The mongodb.Db instance, set when the connection is opened */
db: mongodb.Db;
/** A hash of the collections associated with this connection */
collections: { [index: string]: Collection };
/**
* Connection ready state
* 0 = disconnected
* 1 = connected
* 2 = connecting
* 3 = disconnecting
* Each state change emits its associated event name.
*/
readyState: number;
}
interface ConnectionOptionsBase {
/** passed to the connection db instance */
db?: any;
/** passed to the connection server instance(s) */
server?: any;
/** passed to the connection ReplSet instance */
replset?: any;
/** username for authentication */
user?: string;
/** password for authentication */
pass?: string;
/** options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate) */
auth?: any;
}
/** See the node-mongodb-native driver instance for options that it understands. */
interface ConnectionOpenOptions extends ConnectionOptionsBase {
/** mongoose-specific options */
config?: {
/**
* set to false to disable automatic index creation for all
* models associated with this connection.
*/
autoIndex?: boolean;
};
}
/** See the node-mongodb-native driver instance for options that it understands. */
interface ConnectionOpenSetOptions extends ConnectionOptionsBase {
/**
* If true, enables High Availability support for mongos
* If connecting to multiple mongos servers, set the mongos option to true.
*/
mongos?: boolean;
}
interface ConnectionOptions extends
ConnectionOpenOptions,
ConnectionOpenSetOptions {}
/*
* section drivers/node-mongodb-native/collection.js
* http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-collection-js
*/
var Collection: Collection;
interface Collection extends CollectionBase {
/**
* Collection constructor
* @param name name of the collection
* @param conn A MongooseConnection instance
* @param opts optional collection options
*/
new(name: string, conn: Connection, opts?: Object): Collection;
/** Formatter for debug print args */
$format(arg: any): string;
/** Debug print helper */
$print(name: any, i: any, args: any[]): void;
/** Retreives information about this collections indexes. */
getIndexes(): any;
}
/*
* section drivers/node-mongodb-native/connection.js
* http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-connection-js
*/
class Connection extends ConnectionBase {
/**
* Switches to a different database using the same connection pool.
* @param name The database name
* @returns New Connection Object
*/
useDb(name: string): Connection;
/** Expose the possible connection states. */
static STATES: Object;
}
/*
* section error/validation.js
* http://mongoosejs.com/docs/api.html#error-validation-js
*/
class ValidationError extends Error {
/** Console.log helper */
toString(): string;
}
/*
* section error.js
* http://mongoosejs.com/docs/api.html#error-js
*/
class Error extends global.Error {
/**
* MongooseError constructor
* @param msg Error message
*/
constructor(msg: string);
/**
* The default built-in validator error messages. These may be customized.
* As you might have noticed, error messages support basic templating
* {PATH} is replaced with the invalid document path
* {VALUE} is replaced with the invalid value
* {TYPE} is replaced with the validator type such as "regexp", "min", or "user defined"
* {MIN} is replaced with the declared min value for the Number.min validator
* {MAX} is replaced with the declared max value for the Number.max validator
*/
static messages: Object;
/** For backwards compatibility. Same as mongoose.Error.messages */
static Messages: Object;
}
/*
* section querycursor.js
* http://mongoosejs.com/docs/api.html#querycursor-js
*
* Callback signatures are from: http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close
* QueryCursor can only be accessed by query#cursor(), we only
* expose its interface to enable type-checking.
*/
interface QueryCursor<T extends Document> extends stream.Readable {
/**
* A QueryCursor is a concurrency primitive for processing query results
* one document at a time. A QueryCursor fulfills the Node.js streams3 API,
* in addition to several other mechanisms for loading documents from MongoDB
* one at a time.
* Unless you're an advanced user, do not instantiate this class directly.
* Use Query#cursor() instead.
* @param options query options passed to .find()
* @event cursor Emitted when the cursor is created
* @event error Emitted when an error occurred
* @event data Emitted when the stream is flowing and the next doc is ready
* @event end Emitted when the stream is exhausted
*/
constructor(query: Query<T>, options: Object): QueryCursor<T>;
/** Marks this cursor as closed. Will stop streaming and subsequent calls to next() will error. */
close(callback?: (error: any, result: any) => void): Promise<any>;
/**
* Execute fn for every document in the cursor. If fn returns a promise,
* will wait for the promise to resolve before iterating on to the next one.
* Returns a promise that resolves when done.
* @param callback executed when all docs have been processed
*/
eachAsync(fn: (doc: T) => any, callback?: (err: any) => void): Promise<T>;
/**
* Get the next document from this cursor. Will return null when there are
* no documents left.
*/
next(callback?: (err: any) => void): Promise<any>;
}
/*
* section virtualtype.js
* http://mongoosejs.com/docs/api.html#virtualtype-js
*/
class VirtualType {
/** This is what mongoose uses to define virtual attributes via Schema.prototype.virtual. */
constructor(options: Object, name: string);
/** Applies getters to value using optional scope. */
applyGetters(value: Object, scope: Object): any;
/** Applies setters to value using optional scope. */
applySetters(value: Object, scope: Object): any;
/** Defines a getter. */
get(fn: Function): this;
/** Defines a setter. */
set(fn: Function): this;
}
/*
* section schema.js
* http://mongoosejs.com/docs/api.html#schema-js
*/
class Schema extends events.EventEmitter {
/**
* Schema constructor.
* When nesting schemas, (children in the example above), always declare
* the child schema first before passing it into its parent.
* @event init Emitted after the schema is compiled into a Model.
*/
constructor(definition?: Object, options?: SchemaOptions);
/** Adds key path / schema type pairs to this schema. */
add(obj: Object, prefix?: string): void;
/**
* Iterates the schemas paths similar to Array.forEach.
* @param fn callback function
* @returns this
*/
eachPath(fn: (path: string, type: SchemaType) => void): this;
/**
* Gets a schema option.
* @param key option name
*/
get(key: string): any;
/**
* Defines an index (most likely compound) for this schema.
* @param options Options to pass to MongoDB driver's createIndex() function
* @param options.expires Mongoose-specific syntactic sugar, uses ms to convert
* expires option into seconds for the expireAfterSeconds in the above link.
*/
index(fields: Object, options?: {
expires?: string;
[other: string]: any;
}): this;
/** Compiles indexes from fields and schema-level indexes */
indexes(): any[];
/**
* Adds an instance method to documents constructed from Models compiled from this schema.
* If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods.
*/
method(method: string, fn: Function): this;
method(methodObj: { [name: string]: Function }): this;
/**
* Gets/sets schema paths.
* Sets a path (if arity 2)
* Gets a path (if arity 1)
*/
path(path: string): SchemaType;
path(path: string, constructor: any): this;
/**
* Returns the pathType of path for this schema.
* @returns whether it is a real, virtual, nested, or ad-hoc/undefined path.
*/
pathType(path: string): string;
/**
* Registers a plugin for this schema.
* @param plugin callback
*/
plugin(plugin: (schema: Schema, options?: Object) => void, opts?: Object): this;
/**
* Defines a post hook for the document
* Post hooks fire on the event emitted from document instances of Models compiled
* from this schema.
* @param method name of the method to hook
* @param fn callback
*/
post<T extends Document>(method: string, fn: (doc: T) => void, ...args: any[]): this;
post<T extends Document>(method: string, fn: (doc: T, next: (err?: NativeError) => void,
...otherArgs: any[]) => void): this;
/**
* Defines a pre hook for the document.
*/
pre(method: string, fn: (next: (err?: NativeError) => void) => void,
errorCb?: (err: Error) => void): this;
pre(method: string, parallel: boolean, fn: (next: (err?: NativeError) => void, done: () => void) => void,
errorCb?: (err: Error) => void): this;
/**
* Adds a method call to the queue.
* @param name name of the document method to call later
* @param args arguments to pass to the method
*/
queue(name: string, args: any[]): this;
/**
* Removes the given path (or [paths]).
*/
remove(path: string | string[]): void;
/**
* @param invalidate refresh the cache
* @returns an Array of path strings that are required by this schema.
*/
requiredPaths(invalidate?: boolean): string[];
/**
* Sets/gets a schema option.
* @param key option name
* @param value if not passed, the current option value is returned
*/
set(key: string): any;
set(key: string, value: any): this;
/**
* Adds static "class" methods to Models compiled from this schema.
*/
static(name: string, fn: Function): this;
static(nameObj: { [name: string]: Function }): this;
/** Creates a virtual type with the given name. */
virtual(name: string, options?: Object): VirtualType;
/** Returns the virtual type with the given name. */
virtualpath(name: string): VirtualType;
/** The allowed index types */
static indexTypes: string[];
/**
* Reserved document keys.
* Keys in this object are names that are rejected in schema declarations
* b/c they conflict with mongoose functionality. Using these key name
* will throw an error.
*/
static reserved: Object;
/** Object of currently defined methods on this schema. */
methods: any;
/** Object of currently defined statics on this schema. */
statics: any;
}
interface SchemaOptions {
/** defaults to null (which means use the connection's autoIndex option) */
autoIndex?: boolean;
/** defaults to true */
bufferCommands?: boolean;
/** defaults to false */
capped?: boolean;
/** no default */
collection?: string;
/** defaults to false. */
emitIndexErrors?: boolean;
/** defaults to true */
id?: boolean;
/** defaults to true */
_id?: boolean;
/** controls document#toObject behavior when called manually - defaults to true */
minimize?: boolean;
read?: string;
/** defaults to true. */
safe?: boolean;
/** defaults to null */
shardKey?: boolean;
/** defaults to true */
strict?: boolean;
/** no default */
toJSON?: Object;
/** no default */
toObject?: Object;
/** defaults to 'type' */
typeKey?: string;
/** defaults to false */
useNestedStrict?: boolean;
/** defaults to true */
validateBeforeSave?: boolean;
/** defaults to "__v" */
versionKey?: boolean;
/**
* skipVersioning allows excluding paths from
* versioning (the internal revision will not be
* incremented even if these paths are updated).
*/
skipVersioning?: Object;
/**
* If set timestamps, mongoose assigns createdAt
* and updatedAt fields to your schema, the type
* assigned is Date.
*/
timestamps?: Object;
}
/*
* section document.js
* http://mongoosejs.com/docs/api.html#document-js
*/
class MongooseDocument implements MongooseDocumentOptionals {
/** Checks if a path is set to its default. */
$isDefault(path?: string): boolean;
/**
* Takes a populated field and returns it to its unpopulated state.
* If the path was not populated, this is a no-op.
*/
depopulate(path: string): void;
/**
* Returns true if the Document stores the same data as doc.
* Documents are considered equal when they have matching _ids, unless neither document
* has an _id, in which case this function falls back to usin deepEqual().
* @param doc a document to compare
*/
equals(doc: MongooseDocument): boolean;
/**
* Explicitly executes population and returns a promise.
* Useful for ES2015 integration.
* @returns promise that resolves to the document when population is done
*/
execPopulate(): Promise<this>;
/**
* Returns the value of a path.
* @param type optionally specify a type for on-the-fly attributes
*/
get(path: string, type?: any): any;
/**
* Initializes the document without setters or marking anything modified.
* Called internally after a document is returned from mongodb.
* @param doc document returned by mongo
* @param fn callback
*/
init(doc: MongooseDocument, fn?: () => void): this;
init(doc: MongooseDocument, opts: Object, fn?: () => void): this;
/** Helper for console.log */
inspect(options?: Object): any;
/**
* Marks a path as invalid, causing validation to fail.
* The errorMsg argument will become the message of the ValidationError.
* The value argument (if passed) will be available through the ValidationError.value property.
* @param path the field to invalidate
* @param errorMsg the error which states the reason path was invalid
* @param value optional invalid value
* @param kind optional kind property for the error
* @returns the current ValidationError, with all currently invalidated paths
*/
invalidate(path: string, errorMsg: string | NativeError, value: any, kind?: string): ValidationError | boolean;
/** Returns true if path was directly set and modified, else false. */
isDirectModified(path: string): boolean;
/** Checks if path was initialized */
isInit(path: string): boolean;
/**
* Returns true if this document was modified, else false.
* If path is given, checks if a path or any full path containing path as part of its path
* chain has been modified.
*/
isModified(path?: string): 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.
* Very helpful when using Mixed types.
* @param path the path to mark modified
*/
markModified(path: string): void;
/** Returns the list of paths that have been modified. */
modifiedPaths(): string[];
/**
* Populates document references, executing the callback when complete.
* If you want to use promises instead, use this function with
* execPopulate()
* Population does not occur unless a callback is passed or you explicitly
* call execPopulate(). Passing the same path a second time will overwrite
* the previous path options. See Model.populate() for explaination of options.
* @param path The path to populate or an options object
* @param callback When passed, population is invoked
*/
populate(callback: (err: any, res: this) => void): this;
populate(path: string, callback?: (err: any, res: this) => void): this;
populate(options: ModelPopulateOptions, callback?: (err: any, res: this) => void): this;
/** Gets _id(s) used during population of the given path. If the path was not populated, undefined is returned. */
populated(path: string): any;
/**
* Sets the value of a path, or many paths.
* @param path path or object of key/vals to set
* @param val the value to set
* @param type optionally specify a type for "on-the-fly" attributes
* @param options optionally specify options that modify the behavior of the set
*/
set(path: string, val: any, options?: Object): void;
set(path: string, val: any, type: any, options?: Object): void;
set(value: Object): void;
/**
* The return value of this method is used in calls to JSON.stringify(doc).
* This method accepts the same options as Document#toObject. To apply the
* options to every document of your schema by default, set your schemas
* toJSON option to the same argument.
*/
toJSON(options?: DocumentToObjectOptions): Object;
/**
* Converts this document into a plain javascript object, ready for storage in MongoDB.
* Buffers are converted to instances of mongodb.Binary for proper storage.
*/
toObject(options?: DocumentToObjectOptions): Object;
/** Helper for console.log */
toString(): string;
/**
* Clears the modified state on the specified path.
* @param path the path to unmark modified
*/
unmarkModified(path: string): void;
/** Sends an update command with this document _id as the query selector. */
update(doc: Object, callback?: (err: any, raw: any) => void): Query<any>;
update(doc: Object, options: ModelUpdateOptions,
callback?: (err: any, raw: any) => void): Query<any>;
/**
* Executes registered validation rules for this document.
* @param optional options internal options
* @param callback callback called after validation completes, passing an error if one occurred
*/
validate(callback?: (err: any) => void): Promise<void>;
validate(optional: Object, callback?: (err: any) => void): Promise<void>;
/**
* Executes registered validation rules (skipping asynchronous validators) for this document.
* This method is useful if you need synchronous validation.
* @param pathsToValidate only validate the given paths
* @returns MongooseError if there are errors during validation, or undefined if there is no error.
*/
validateSync(pathsToValidate: string | string[]): Error;
/** Hash containing current validation errors. */
errors: Object;
/** This documents _id. */
_id: any;
/** Boolean flag specifying if the document is new. */
isNew: boolean;
/** The documents schema. */
schema: Schema;
}
interface MongooseDocumentOptionals {
/** The string version of this documents _id. */
id?: string;
}
interface DocumentToObjectOptions {
/** apply all getters (path and virtual getters) */
getters?: boolean;
/** apply virtual getters (can override getters option) */
virtuals?: boolean;
/** remove empty objects (defaults to true) */
minimize?: boolean;
/**
* A transform function to apply to the resulting document before returning
* @param doc The mongoose document which is being converted
* @param ret The plain object representation which has been converted
* @param options The options in use (either schema options or the options passed inline)
*/
transform?: (doc: any, ret: Object, options: Object) => any;
/** depopulate any populated paths, replacing them with their original refs (defaults to false) */
depopulate?: boolean;
/** whether to include the version key (defaults to true) */
versionKey?: boolean;
/**
* keep the order of object keys. If this is set to true,
* Object.keys(new Doc({ a: 1, b: 2}).toObject()) will
* always produce ['a', 'b'] (defaults to false)
*/
retainKeyOrder?: boolean;
}
namespace Types {
/*
* section types/subdocument.js
* http://mongoosejs.com/docs/api.html#types-subdocument-js
*/
class Subdocument extends MongooseDocument {
/** Returns the top level document of this sub-document. */
ownerDocument(): MongooseDocument;
/**
* Null-out this subdoc
* @param callback optional callback for compatibility with Document.prototype.remove
*/
remove(callback?: (err: any) => void): void;
remove(options: Object, callback?: (err: any) => void): void;
}
/*
* section types/array.js
* http://mongoosejs.com/docs/api.html#types-array-js
*/
class Array<T> extends global.Array<T> {
/**
* Atomically shifts the array at most one time per document save().
* Calling this mulitple times on an array before saving sends the same command as
* calling it once. This update is implemented using the MongoDB $pop method which
* enforces this restriction.
*/
$shift(): T;
/** Alias of pull */
remove(...args: any[]): this;
/**
* Pops the array atomically at most one time per document save().
* Calling this mulitple times on an array before saving sends the same command as
* calling it once. This update is implemented using the MongoDB $pop method which
* enforces this restriction.
*/
$pop(): T;
/**
* Adds values to the array if not already present.
* @returns the values that were added
*/
addToSet(...args: any[]): T[];
/**
* Return the index of obj or -1 if not found.
* @param obj he item to look for
*/
indexOf(obj: any): number;
/** Helper for console.log */
inspect(): any;
/**
* Marks the entire array as modified, which if saved, will store it as a $set
* operation, potentially overwritting any changes that happen between when you
* retrieved the object and when you save it.
* @returns new length of the array
*/
nonAtomicPush(...args: any[]): number;
/**
* Wraps Array#pop with proper change tracking.
* marks the entire array as modified which will pass the entire thing to $set
* potentially overwritting any changes that happen between when you retrieved
* the object and when you save it.
*/
pop(): T;
/**
* Pulls items from the array atomically. Equality is determined by casting
* the provided value to an embedded document and comparing using
* the Document.equals() function.
*/
pull(...args: any[]): this;
/**
* Wraps Array#push with proper change tracking.
* @returns new length of the array
*/
push(...args: any[]): number;
/** Sets the casted val at index i and marks the array modified. */
set(i: number, val: any): this;
/**