@types/mongoose
Version:
TypeScript definitions for Mongoose
1,388 lines (1,216 loc) • 136 kB
TypeScript
// Type definitions for Mongoose 5.3.4
// Project: http://mongoosejs.com/
// Definitions by: horiuchi <https://github.com/horiuchi>
// lukasz-zak <https://github.com/lukasz-zak>
// Alorel <https://github.com/Alorel>
// jendrikw <https://github.com/jendrikw>
// Ethan Resnick <https://github.com/ethanresnick>
// vologa <https://github.com/vologab>
// jussikinnula <https://github.com/jussikinnula>
// ondratra <https://github.com/ondratra>
// alfirin <https://github.com/alfirin>
// Idan Dardikman <https://github.com/idandrd>
// Dominik Heigl <https://github.com/various89>
// Fazendaaa <https://github.com/Fazendaaa>
// Norman Perrin <https://github.com/NormanPerrin>
// Dan Manastireanu <https://github.com/danmana>
// stablio <https://github.com/stablio>
// Emmanuel Gautier <https://github.com/emmanuelgautier>
// Frontend Monster <https://github.com/frontendmonster>
// Ming Chen <https://github.com/mingchen>
// Olga Isakova <https://github.com/penumbra1>
// Orblazer <https://github.com/orblazer>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="mongodb" />
/// <reference types="node" />
/*
* 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.
*/
/*
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');
/**
* Gets and optionally overwrites the function used to pluralize collection names
* @param fn function to use for pluralization of collection names
* @returns the current function used to pluralize collection names (defaults to the `mongoose-legacy-pluralize` module's function)
*/
export function pluralize(fn?: (str: string) => string): (str: string) => string;
/*
* 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: any;
/** The default connection of the mongoose module. */
export var connection: Connection;
/** Models registred on the default mongoose connection. */
export var models: { [index: string]: Model<any> };
/** 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): null;
export function connect(uris: string, callback: (err: mongodb.MongoError) => void): null;
export function connect(uris: string, options?: ConnectionOptions): Promise<Mongoose>;
/**
* 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 & {
then: Promise<Connection>["then"];
catch: Promise<Connection>["catch"];
};
/**
* Disconnects all connections.
* @param fn called after all connection close.
*/
export function disconnect(fn: (error?: any) => void): null;
/** Disconnects all connections. */
export function disconnect(): Promise<void>;
/** 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): typeof mongoose;
export function plugin<T>(fn: Function, opts: T): typeof mongoose;
/** Sets mongoose options */
export function set(key: string, value: any): void;
export function startSession(options?: mongodb.SessionOptions, cb?: (err: any, session: mongodb.ClientSession) => void): Promise<mongodb.ClientSession>;
export type CastError = Error.CastError;
/*
* 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.
* @deprecated open() is deprecated in mongoose >= 4.11.0
* @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 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.
*/
openUri(connection_string: string, database?: string, port?: number,
options?: ConnectionOpenOptions, callback?: (err: any) => void): any;
/** Helper for dropDatabase() */
dropDatabase(callback?: (err: any) => void): Promise<any>;
/** Helper for creating a collection */
createCollection(name: string, options?: mongodb.CollectionCreateOptions, cb?: (err: any, collection: mongodb.Collection) => void): Promise<void>;
/** Helper for dropCollection() */
dropCollection(name: string, callback?: (err: any) => void): Promise<void>;
/**
* 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>;
/** Closes the connection */
close(force?: boolean, 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?: any): 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;
/**
* 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.
*
* @param name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp.
* @returns this
*/
deleteModel(name: string | RegExp): Connection;
/** 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: any;
/** 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 };
/** A hash of models registered with this connection */
models: { [index: string]: Model<any> };
/**
* Connection ready state
* 0 = disconnected
* 1 = connected
* 2 = connecting
* 3 = disconnecting
* Each state change emits its associated event name.
*/
readyState: number;
}
/**
* Connection optional settings.
*
* see
* https://mongoosejs.com/docs/api.html#mongoose_Mongoose-connect
* and
* http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html
* for all available options.
*
*/
interface ConnectionOptionsBase {
/** database Name for Mongodb Atlas Connection */
dbName?: string;
/** 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;
/** Use ssl connection (needs to have a mongod server with ssl support) (default: true) */
ssl?: boolean;
/** Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) */
sslValidate?: boolean;
/** Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. */
poolSize?: number;
/** Reconnect on error (default: true) */
autoReconnect?: boolean;
/** TCP Connection keep alive enabled (default: true) */
keepAlive?: boolean;
/** The number of milliseconds to wait before initiating keepAlive on the TCP socket (default 30000) */
keepAliveInitialDelay?: number;
/** TCP Connection timeout setting (default: 30000) */
connectTimeoutMS?: number;
/** TCP Socket timeout setting (default: 360000) */
socketTimeoutMS?: number;
/** If the database authentication is dependent on another databaseName. */
authSource?: string;
/** If you're connected to a single server or mongos proxy (as opposed to a replica set),
* the MongoDB driver will try to reconnect every reconnectInterval milliseconds for reconnectTries
* times, and give up afterward. When the driver gives up, the mongoose connection emits a
* reconnectFailed event. (default: 30) */
reconnectTries?: number;
/** Will wait # milliseconds between retries (default: 1000) */
reconnectInterval?: number;
/** The name of the replicaset to connect to. */
replicaSet?: string;
/** The current value of the parameter native_parser */
nativeParser?: boolean;
/** Auth mechanism */
authMechanism?: any;
/** Specify a journal write concern (default: false). */
journal?: boolean;
/** The write concern */
w?: number | string;
/** The write concern timeout. */
wTimeoutMS?: number;
/** The ReadPreference mode as listed here: http://mongodb.github.io/node-mongodb-native/2.1/api/ReadPreference.html */
readPreference?: string;
/** An object representing read preference tags, see: http://mongodb.github.io/node-mongodb-native/2.1/api/ReadPreference.html */
readPreferencetags?: object;
/** Triggers the server instance to call ismaster (default: true). */
monitoring?: boolean;
/** The interval of calling ismaster when monitoring is enabled (default: 10000). */
haInterval?: number;
/** Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit (default: false). */
domainsEnabled?: boolean;
/** How long driver keeps waiting for servers to come back up (default: Number.MAX_VALUE) */
bufferMaxEntries?: number;
/** additional SSL configuration options */
/** Array of valid certificates either as Buffers or Strings */
sslCA?: ReadonlyArray<Buffer | string>;
/** Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) */
sslCRL?: ReadonlyArray<Buffer | string>;
/** SSL certificate */
sslCert?: Buffer | string;
/** SSL private key */
sslKey?: Buffer | string;
/** SSL Certificate pass phrase */
sslPass?: Buffer | string;
/** Default: true; Server identity checking during SSL */
checkServerIdentity?: boolean | Function;
/** String containing the server name requested via TLS SNI. */
servername?: string;
/** Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. */
ciphers?: string;
ecdhCurve?: string;
/** Flag for using new URL string parser instead of current (deprecated) one */
useNewUrlParser?: boolean;
/** Set to false to make findOneAndUpdate() and findOneAndRemove() use native findOneAndUpdate() rather than findAndModify(). */
useFindAndModify?: boolean;
/** If true, this connection will use createIndex() instead of ensureIndex() for automatic index builds via Model.init(). */
useCreateIndex?: boolean;
// TODO
safe?: any;
fsync?: any;
rs_name?: any;
slaveOk?: any;
authdb?: 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;
};
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;
/** sets the underlying driver's promise library (see http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html) */
promiseLibrary?: any;
/** See http://mongoosejs.com/docs/connections.html#use-mongo-client **/
useMongoClient?: boolean;
/** See http://mongoosejs.com/docs/guide.html#bufferCommands */
bufferCommands?: boolean;
}
interface ConnectionOptions extends
ConnectionOpenOptions,
ConnectionOpenSetOptions { }
interface ClientSession extends mongodb.ClientSession { }
/*
* 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?: 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;
}
/*
* 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;
startSession(options?: mongodb.SessionOptions, cb?: (err: any, session: mongodb.ClientSession) => void): Promise<mongodb.ClientSession>;
/** Expose the possible connection states. */
static STATES: any;
}
/*
* section error.js
* http://mongoosejs.com/docs/api.html#error-js
*/
class Error extends global.Error {
// "MongooseError" for instances of the current class,
// an other string for instances of derived classes.
name: "MongooseError" | string;
/**
* 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: any;
/** For backwards compatibility. Same as mongoose.Error.messages */
static Messages: any;
}
module Error {
/**
* section error/notFound.js
* https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.DocumentNotFoundError
*
* An instance of this error class will be returned when `save()` fails
* because the underlying
* document was not found. The constructor takes one parameter, the
* conditions that mongoose passed to `update()` when trying to update
* the document.
*/
export class DocumentNotFoundError extends Error {
name: 'DocumentNotFoundError';
filter: any;
query: any;
constructor(filter: any);
}
/**
* section error/cast.js
* https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.CastError
*
* An instance of this error class will be returned when mongoose failed to
* cast a value.
*/
export class CastError extends Error {
name: 'CastError';
stringValue: string;
kind: string;
value: any;
path: string;
reason?: any;
model?: any;
constructor(type: string, value: any, path: string, reason?: NativeError);
setModel(model: any): void;
}
/**
* section error/validation.js
* https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ValidationError
* An instance of this error class will be returned when [validation](/docs/validation.html) failed.
* The `errors` property contains an object whose keys are the paths that failed and whose values are
* instances of CastError or ValidationError.
*
*/
export class ValidationError extends Error {
name: 'ValidationError';
errors: {[path: string]: ValidatorError | CastError};
constructor(instance?: MongooseDocument);
/** Console.log helper */
toString(): string;
inspect(): object;
toJSON(): object;
addError(path: string, error: any): void;
}
/**
* section error/validator.js
* https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ValidatorError
*
* A `ValidationError` has a hash of `errors` that contain individual `ValidatorError` instances
*/
export class ValidatorError extends Error {
name: 'ValidatorError';
properties: {message: string, type?: string, path?: string, value?: any, reason?: any};
kind: string;
path: string;
value: any;
reason: any;
constructor(properties: {message?: string, type?: string, path?: string, value?: any, reason?: any});
formatMessage(msg: string | Function, properties: any): string;
toString(): string;
}
/**
* section error/version.js
* https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.VersionError
*
* An instance of this error class will be returned when you call `save()` after
* the document in the database was changed in a potentially unsafe way. See
* the [`versionKey` option](http://mongoosejs.com/docs/guide.html#versionKey) for more information.
*/
export class VersionError extends Error {
name: 'VersionError';
version: any;
modifiedPaths: Array<any>;
constructor(doc: MongooseDocument, currentVersion: any, modifiedPaths: any);
}
/**
* section error/parallelSave.js
* https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ParallelSaveError
*
* An instance of this error class will be returned when you call `save()` multiple
* times on the same document in parallel. See the [FAQ](http://mongoosejs.com/docs/faq.html) for more
* information.
*/
export class ParallelSaveError extends Error {
name: 'ParallelSaveError';
constructor(doc: MongooseDocument);
}
/**
* section error/overwriteModel.js
* https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.OverwriteModelError
*
* Thrown when a model with the given name was already registered on the connection.
* See [the FAQ about `OverwriteModelError`](http://mongoosejs.com/docs/faq.html#overwrite-model-error).
*/
export class OverwriteModelError extends Error {
name: 'OverwriteModelError';
constructor(name: string);
}
/**
* section error/missingSchema.js
* https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.MissingSchemaError
*
* Thrown when you try to access a model that has not been registered yet
*/
export class MissingSchemaError extends Error {
name: 'MissingSchemaError';
constructor(name: string);
}
/**
* section error/divergentArray.js
* https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.DivergentArrayError
*
* An instance of this error will be returned if you used an array projection
* and then modified the array in an unsafe way.
*/
export class DivergentArrayError extends Error {
name: 'DivergentArrayError';
constructor(paths: Array<any>);
}
}
interface EachAsyncOptions {
/** defaults to 1 */
parallel?: number;
}
/*
* 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: any): 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 fn Function to be executed for every document in the cursor
* @param callback Executed when all docs have been processed
*/
eachAsync(fn: (doc: T) => any, callback?: (err: any) => void): Promise<T>;
/**
* 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 fn Function to be executed for every document in the cursor
* @param options Async options (e. g. parallel function execution)
* @param callback Executed when all docs have been processed
*/
eachAsync(fn: (doc: T) => any, options: EachAsyncOptions, callback?: (err: any) => void): Promise<T>;
/**
* Registers a transform function which subsequently maps documents retrieved
* via the streams interface or .next()
*/
map(fn: (doc: T) => T): this;
/**
* Get the next document from this cursor. Will return null when there are
* no documents left.
*/
next(callback?: (err: any, doc?: T) => 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: any, name: string);
/** Applies getters to value using optional scope. */
applyGetters(value: any, scope: any): any;
/** Applies setters to value using optional scope. */
applySetters(value: any, scope: any): 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<T = any> 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?: SchemaDefinition, options?: SchemaOptions);
/** Adds key path / schema type pairs to this schema. */
add(obj: SchemaDefinition, prefix?: string): void;
/** Return a deep copy of this schema */
clone(): Schema;
/**
* 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: any, options?: {
expires?: string;
[other: string]: any;
}): this;
/** Compiles indexes from fields and schema-level indexes */
indexes(): any[];
/**
* Loads an ES6 class into a schema. Maps setters + getters, static methods, and
* instance methods to schema virtuals, statics, and methods.
*/
loadClass(model: Function): this;
/**
* 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<F extends keyof T>(method: F, fn: T[F]): this;
method(methodObj: {
[F in keyof T]: T[F]
}): 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) => void): this;
plugin<T>(plugin: (schema: Schema, options: T) => void, opts: T): 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, next: (err?: NativeError) => void
) => void): this;
post<T extends Document>(method: string, fn: (
error: mongodb.MongoError, doc: T, next: (err?: NativeError) => void
) => void): this;
/**
* Defines a pre hook for the document.
*/
pre<T extends Document = Document>(
method: "init" | "validate" | "save" | "remove",
fn: HookSyncCallback<T>,
errorCb?: HookErrorCallback
): this;
pre<T extends Query<any> = Query<any>>(
method:
| "count"
| "find"
| "findOne"
| "findOneAndRemove"
| "findOneAndUpdate"
| "update"
| "updateOne"
| "updateMany",
fn: HookSyncCallback<T>,
errorCb?: HookErrorCallback
): this;
pre<T extends Aggregate<any> = Aggregate<any>>(
method: "aggregate",
fn: HookSyncCallback<T>,
errorCb?: HookErrorCallback
): this;
pre<T extends Model<Document> = Model<Document>>(
method: "insertMany",
fn: HookSyncCallback<T>,
errorCb?: HookErrorCallback
): this;
pre<T extends Document | Model<Document> | Query<any> | Aggregate<any>>(
method: string,
fn: HookSyncCallback<T>,
errorCb?: HookErrorCallback
): this;
pre<T extends Document = Document>(
method: "init" | "validate" | "save" | "remove",
parallel: boolean,
fn: HookAsyncCallback<T>,
errorCb?: HookErrorCallback
): this;
pre<T extends Query<any> = Query<any>>(
method:
| "count"
| "find"
| "findOne"
| "findOneAndRemove"
| "findOneAndUpdate"
| "update"
| "updateOne"
| "updateMany",
parallel: boolean,
fn: HookAsyncCallback<T>,
errorCb?: HookErrorCallback
): this;
pre<T extends Aggregate<any> = Aggregate<any>>(
method: "aggregate",
parallel: boolean,
fn: HookAsyncCallback<T>,
errorCb?: HookErrorCallback
): this;
pre<T extends Model<Document> = Model<Document>>(
method: "insertMany",
parallel: boolean,
fn: HookAsyncCallback<T>,
errorCb?: HookErrorCallback
): this;
pre<T extends Document | Model<Document> | Query<any> | Aggregate<any>>(
method: string,
parallel: boolean,
fn: HookAsyncCallback<T>,
errorCb?: HookErrorCallback
): 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<T extends keyof SchemaOptions>(key: T): SchemaOptions[T];
set<T extends keyof SchemaOptions>(key: T, value: SchemaOptions[T]): 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?: any): 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: any;
/** Object of currently defined methods on this schema. */
methods: {
[F in keyof T]: T[F]
};
/** Object of currently defined statics on this schema. */
statics: any;
/** Object of currently defined query helpers on this schema. */
query: any;
/** The original object passed to the schema constructor */
obj: any;
}
// Hook functions: https://github.com/vkarpov15/hooks-fixed
interface HookSyncCallback<T> {
(this: T, next: HookNextFunction, docs: any[]): Promise<any> | void;
}
interface HookAsyncCallback<T> {
(this: T, next: HookNextFunction, done: HookDoneFunction, docs: any[]): Promise<any> | void;
}
interface HookErrorCallback {
(error?: Error): any;
}
interface HookNextFunction {
(error?: Error): any;
}
interface HookDoneFunction {
(error?: Error): any;
}
interface SchemaOptions {
/** defaults to false (which means use the connection's autoIndex option) */
autoIndex?: boolean;
/** defaults to true */
bufferCommands?: boolean;
/** defaults to false */
capped?: boolean | number | { size?: number; max?: number; autoIndexId?: boolean; };
/** Sets a default collation for every query and aggregation. */
collation?: CollationOptions;
/** no default */
collection?: string;
/** defaults to "__t" */
discriminatorKey?: string;
/** defaults to false. */
emitIndexErrors?: boolean;
excludeIndexes?: any;
/** defaults to true */
id?: boolean;
/** defaults to true */
_id?: boolean;
/** controls document#toObject behavior when called manually - defaults to true */
minimize?: boolean;
read?: string;
writeConcern?: WriteConcern;
/** defaults to true. */
safe?: boolean | { w?: number | string; wtimeout?: number; j?: boolean };
/** defaults to null */
shardKey?: boolean;
/** defaults to true */
strict?: boolean | 'throw';
/** no default */
toJSON?: DocumentToObjectOptions;
/** no default */
toObject?: DocumentToObjectOptions;
/** defaults to 'type' */
typeKey?: string;
/** defaults to false */
useNestedStrict?: boolean;
/** defaults to false */
usePushEach?: boolean;
/** defaults to true */
validateBeforeSave?: boolean;
/** defaults to "__v" */
versionKey?: string | boolean;
/**
* By default, Mongoose will automatically
* select() any populated paths.
* To opt out, set selectPopulatedPaths to false.
*/
selectPopulatedPaths?: boolean;
/**
* skipVersioning allows excluding paths from
* versioning (the internal revision will not be
* incremented even if these paths are updated).
*/
skipVersioning?: any;
/**
* Validation errors in a single nested schema are reported
* both on the child and on the parent schema.
* Set storeSubdocValidationError to false on the child schema
* to make Mongoose only report the parent error.
*/
storeSubdocValidationError?: boolean;
/**
* If set timestamps, mongoose assigns createdAt
* and updatedAt fields to your schema, the type
* assigned is Date.
*/
timestamps?: boolean | SchemaTimestampsConfig;
}
interface SchemaTimestampsConfig {
createdAt?: boolean | string;
updatedAt?: boolean | string;
}
/*
* Intellisense for Schema definitions
*/
interface SchemaDefinition {
[path: string]: SchemaTypeOpts<any> | Schema | SchemaType;
}
/*
* The standard options available when configuring a schema type:
* new Schema({
* name: {
* type: String,
* required: true,
* ...
* }
* });
*
* Note: the properties have Object as a fallback type: | Object
* because this interface does not apply to a schematype that
* does not have a type property. Ex:
* new Schema({
* name: {
* first: String, // since name does not have a "type" property
* last: String // first and last can have any valid type
* ...
* }
* });
*
* References:
* - http://mongoosejs.com/docs/schematypes.html
* - http://mongoosejs.com/docs/api.html#schema_Schema.Types
*/
interface SchemaTypeOpts<T> {
alias?: string;
/* Common Options for all schema types */
type?: T;
/** Sets a default value for this SchemaType. */
default?: SchemaTypeOpts.DefaultFn<T> | T;
/**
* Getters allow you to transform the representation of the data as it travels
* from the raw mongodb document to the value that you see.
*/
get?: (value: T, schematype?: this) => T | any;
/** Declares the index options for this schematype. */
index?: SchemaTypeOpts.IndexOpts | boolean | string;
/**
* Adds a required validator to this SchemaType. The validator gets added
* to the front of this SchemaType's validators array using unshift().
*/
required?: SchemaTypeOpts.RequiredFn<T> |
boolean | [boolean, string] |
string | [string, string] |
any;
/**
* Sets default select() behavior for this path.
* Set to true if this path should always be included in the results, false
* if it should be excluded by default. This setting can be overridden at
* the query level.
*/
select?: boolean | any;
/**
* Setters allow you to transform the data before it gets to the raw mongodb
* document and is set as a value on an actual key.
*/
set?: (value: T, schematype?: this) => T | any;
/** Declares a sparse index. */
sparse?: boolean | any;
/** Declares a full text index. */
text?: boolean | any;
/**
* Adds validator(s) for this document path.
* Validators always receive the value to validate as their first argument
* and must return Boolean. Returning false means validation failed.
*/
validate?: RegExp | [RegExp, string] |
SchemaTypeOpts.ValidateFn<T> | [SchemaTypeOpts.ValidateFn<T>, string] |
SchemaTypeOpts.ValidateOpts | SchemaTypeOpts.AsyncValidateOpts |
SchemaTypeOpts.AsyncPromiseValidationFn<T> | SchemaTypeOpts.AsyncPromiseValidationOpts |
(SchemaTypeOpts.ValidateOpts | SchemaTypeOpts.AsyncValidateOpts |
SchemaTypeOpts.AsyncPromiseValidationFn<T> | SchemaTypeOpts.AsyncPromiseValidationOpts)[];
/** Declares an unique index. */
unique?: boolean | any;
/* Options for specific schema types (String, Number, Date, etc.) */
/** String only - Adds an enum validator */
enum?: T[] | SchemaTypeOpts.EnumOpts<T> | any;
/** String only - Adds a lowercase setter. */
lowercase?: boolean | any;
/** String only - Sets a regexp validator. */
match?: RegExp | [RegExp, string] | any;
/** String only - Sets a maximum length validator. */
maxlength?: number | [number, string] | any;
/** String only - Sets a minimum length validator. */
minlength?: number | [number, string] | any;
/** String only - Adds a trim setter. */
trim?: boolean | any;
/** String only - Adds an uppercase setter. */
uppercase?: boolean | any;
/**
* Date, Number only - Sets a minimum number validator.
* Sets a minimum date validator.
*/
min?: number | [number, string] |
Date | [Date, string] |
any;
/**
* Date, Number only - Sets a maximum number validator.
* Sets a maximum date validator.
*/
max?: number | [number, string] |
Date | [Date, string] |
any;
/**
* Date only - Declares a TTL index (rounded to the nearest second)
* for Date types only.
*/
expires?: number | string | any;
/** ObjectId only - Adds an auto-generated ObjectId default if turnOn is true. */
auto?: boolean | any;
[other: string]: any;
}
// Interfaces specific to schema type options should be scoped in this namespace
namespace SchemaTypeOpts {
interface DefaultFn<T> {
(...args: any[]): T;
}
interface RequiredFn<T> {
(required: boolean, message?: string): T;
}
interface ValidateFn<T> {
(value: T): boolean;
}
interface AsyncValidateFn<T> {
(value: T, done: (result: boolean) => void): void;
}
interface ValidateOptsBase {
msg?: string;
type?: string;
}
interface ValidateOpts extends ValidateOptsBase {
isAsync?: false;
validator?: RegExp | ValidateFn<any>;
}
interface AsyncValidateOpts extends ValidateOptsBase {
isAsync: true;
validator: AsyncValidateFn<any>;
}
interface AsyncPromiseValidationFn<T> {
(value: T): Promise<boolean>;
}
interface AsyncPromiseValidationOpts extends ValidateOptsBase {
validator: AsyncPromiseValidationFn<any>;
}
interface EnumOpts<T> {
values?: T[];
message?: string;
}
interface IndexOpts {
background?: boolean,
expires?: number | string
sparse?: boolean,
type?: string,
unique?: boolean,
}
}
/*
* section document.js
* http://mongoosejs.com/docs/api.html#document-js
*/
interface MongooseDocument extends MongooseDocumentOptionals { }
class MongooseDocument {
/** Checks if a path is set to its default. */
$isDefault(path?: string): boolean;
/** Getter/setter around the session associated with this document. */
$session(session?: ClientSession): ClientSession;
/**
* 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): this;
/**
* 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>;
/** Checks if path was explicitly selected. If no projection, always returns true. */
isDirectSelected(path: string): boolean;
/**
* 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 opts Options
*/
init(doc: MongooseDocument, opts?: any): this;
/** Helper for console.log */
inspect(options?: any): 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): Error.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 optio