///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
declare class NativeDate extends global.Date { }
declare module 'mongoose' {
import events = require('events');
import mongodb = require('mongodb');
import mongoose = require('mongoose');
export type Mongoose = typeof mongoose;
/**
* Mongoose constructor. The exports object of the `mongoose` module is an instance of this
* class. Most apps will only use this one instance.
*/
export const Mongoose: new (options?: MongooseOptions | null) => Mongoose;
export let Promise: any;
export const PromiseProvider: any;
/**
* Can be extended to explicitly type specific models.
*/
export interface Models {
[modelName: string]: Model
}
/** An array containing all models associated with this Mongoose instance. */
export const models: Models;
/**
* 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): Mongoose;
/**
* Sanitizes query filters against query selector injection attacks by wrapping
* any nested objects that have a property whose name starts with `$` in a `$eq`.
*/
export function sanitizeFilter(filter: FilterQuery): FilterQuery;
/** Gets mongoose options */
export function get(key: K): MongooseOptions[K];
/* ! ignore */
export type CompileModelOptions = {
overwriteModels?: boolean,
connection?: Connection
};
export function model(
name: string,
schema?: TSchema,
collection?: string,
options?: CompileModelOptions
): Model, ObtainSchemaGeneric, ObtainSchemaGeneric, {}, TSchema> & ObtainSchemaGeneric;
export function model(name: string, schema?: Schema | Schema, collection?: string, options?: CompileModelOptions): Model;
export function model(
name: string,
schema?: Schema,
collection?: string,
options?: CompileModelOptions
): U;
/** Returns an array of model names created on this instance of Mongoose. */
export function modelNames(): Array;
/**
* Overwrites the current driver used by this Mongoose instance. A driver is a
* Mongoose-specific interface that defines functions like `find()`.
*/
export function setDriver(driver: any): Mongoose;
/** The node-mongodb-native driver Mongoose uses. */
export const mongo: typeof mongodb;
/** Declares a global plugin executed on all Schemas. */
export function plugin(fn: (schema: Schema, opts?: any) => void, opts?: any): Mongoose;
/** Getter/setter around function for pluralizing collection names. */
export function pluralize(fn?: ((str: string) => string) | null): ((str: string) => string) | null;
/** Sets mongoose options */
export function set(key: K, value: MongooseOptions[K]): Mongoose;
/** The Mongoose version */
export const version: string;
export type AnyKeys = { [P in keyof T]?: T[P] | any };
export interface AnyObject {
[k: string]: any
}
export type Require_id = T extends { _id?: infer U }
? IfAny>
: T & { _id: Types.ObjectId };
export type HydratedDocument = DocType extends Document ? Require_id : (Document & Require_id & TVirtuals & TMethodsAndOverrides);
export type HydratedDocumentFromSchema = HydratedDocument<
InferSchemaType,
ObtainSchemaGeneric,
ObtainSchemaGeneric
>;
export interface TagSet {
[k: string]: string;
}
export interface ToObjectOptions {
/** apply all getters (path and virtual getters) */
getters?: boolean;
/** apply virtual getters (can override getters option) */
virtuals?: boolean | string[];
/** if `options.virtuals = true`, you can set `options.aliases = false` to skip applying aliases. This option is a no-op if `options.virtuals = false`. */
aliases?: boolean;
/** remove empty objects (defaults to true) */
minimize?: boolean;
/** if set, mongoose will call this function to allow you to transform the returned object */
transform?: boolean | ((doc: any, ret: any, options: any) => any);
/** if true, replace any conventionally populated paths with the original id in the output. Has no affect on virtual populated paths. */
depopulate?: boolean;
/** if false, exclude the version key (`__v` by default) from the output */
versionKey?: boolean;
/** if true, convert Maps to POJOs. Useful if you want to `JSON.stringify()` the result of `toObject()`. */
flattenMaps?: boolean;
/** If true, omits fields that are excluded in this document's projection. Unless you specified a projection, this will omit any field that has `select: false` in the schema. */
useProjection?: boolean;
}
export type DiscriminatorModel = T extends Model
?
M extends Model
? Model & T1, M2 | T2, M3 | T3, M4 | T4>
: M
: M;
export type DiscriminatorSchema =
DisSchema extends Schema
? Schema & DisSchemaEDocType, DiscriminatorModel, DisSchemaInstanceMethods | TInstanceMethods, DisSchemaQueryhelpers | TQueryHelpers, DisSchemaVirtuals | TVirtuals, DisSchemaStatics & TStaticMethods>
: Schema;
type QueryResultType = T extends Query ? ResultType : never;
type PluginFunction<
DocType,
M,
TInstanceMethods,
TQueryHelpers,
TVirtuals,
TStaticMethods> = (schema: Schema, opts?: any) => void;
export class Schema<
EnforcedDocType = any,
M = Model,
TInstanceMethods = {},
TQueryHelpers = {},
TVirtuals = {},
TStaticMethods = {},
TPathTypeKey extends TypeKeyBaseType = DefaultTypeKey,
DocType extends ObtainDocumentType = ObtainDocumentType>
extends events.EventEmitter {
/**
* Create a new schema
*/
constructor(definition?: SchemaDefinition> | DocType, options?: SchemaOptions, TInstanceMethods, TQueryHelpers, TStaticMethods, TVirtuals>);
/** Adds key path / schema type pairs to this schema. */
add(obj: SchemaDefinition> | Schema, prefix?: string): this;
/**
* Array of child schemas (from document arrays and single nested subdocs)
* and their corresponding compiled models. Each element of the array is
* an object with 2 properties: `schema` and `model`.
*/
childSchemas: { schema: Schema, model: any }[];
/** Removes all indexes on this schema */
clearIndexes(): this;
/** Returns a copy of this schema */
clone(): T;
discriminator(name: string, schema: DisSchema): DiscriminatorSchema;
/** Returns a new schema that has the picked `paths` from this schema. */
pick(paths: string[], options?: SchemaOptions): T;
/** Object containing discriminators defined on this schema */
discriminators?: { [name: string]: Schema };
/** Iterates the schemas paths similar to Array#forEach. */
eachPath(fn: (path: string, type: SchemaType) => void): this;
/** Defines an index (most likely compound) for this schema. */
index(fields: IndexDefinition, options?: IndexOptions): this;
/**
* Returns a list of indexes that this schema declares, via `schema.index()`
* or by `index: true` in a path's options.
*/
indexes(): Array;
/** Gets a schema option. */
get(key: K): SchemaOptions[K];
/**
* Loads an ES6 class into a schema. Maps [setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) + [getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get), [static methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static),
* and [instance methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions)
* to schema [virtuals](http://mongoosejs.com/docs/guide.html#virtuals),
* [statics](http://mongoosejs.com/docs/guide.html#statics), and
* [methods](http://mongoosejs.com/docs/guide.html#methods).
*/
loadClass(model: Function, onlyVirtuals?: boolean): this;
/** Adds an instance method to documents constructed from Models compiled from this schema. */
method(name: string, fn: (this: Context, ...args: any[]) => any, opts?: any): this;
method(obj: Partial): this;
/** Object of currently defined methods on this schema. */
methods: { [F in keyof TInstanceMethods]: TInstanceMethods[F] } & AnyObject;
/** The original object passed to the schema constructor */
obj: SchemaDefinition>;
/** Gets/sets schema paths. */
path(path: pathGeneric): SchemaType;
path(path: string): ResultType;
path(path: string, constructor: any): this;
/** Lists all paths and their type in the schema. */
paths: {
[key: string]: SchemaType;
};
/** Returns the pathType of `path` for this schema. */
pathType(path: string): string;
/** Registers a plugin for this schema. */
plugin, POptions extends Parameters[1] = Parameters[1]>(fn: PFunc, opts?: POptions): this;
/** Defines a post hook for the model. */
post>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, fn: PostMiddlewareFunction): this;
post>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction): this;
post>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, fn: PostMiddlewareFunction>): this;
post>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction>): this;
post>(method: 'aggregate' | RegExp, fn: PostMiddlewareFunction>>): this;
post>(method: 'aggregate' | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction>>): this;
post(method: 'insertMany' | RegExp, fn: PostMiddlewareFunction): this;
post(method: 'insertMany' | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction): this;
post>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, fn: ErrorHandlingMiddlewareFunction): this;
post>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction): this;
post>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, fn: ErrorHandlingMiddlewareFunction): this;
post>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction): this;
post>(method: 'aggregate' | RegExp, fn: ErrorHandlingMiddlewareFunction>): this;
post>(method: 'aggregate' | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction>): this;
post(method: 'insertMany' | RegExp, fn: ErrorHandlingMiddlewareFunction): this;
post(method: 'insertMany' | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction): this;
/** Defines a pre hook for the model. */
pre>(method: 'save', fn: PreSaveMiddlewareFunction): this;
pre>(method: 'save', options: SchemaPreOptions, fn: PreSaveMiddlewareFunction): this;
pre>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, fn: PreMiddlewareFunction): this;
pre>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction): this;
pre>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, fn: PreMiddlewareFunction): this;
pre>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction): this;
pre>(method: 'aggregate' | RegExp, fn: PreMiddlewareFunction): this;
pre>(method: 'aggregate' | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction): this;
pre(method: 'insertMany' | RegExp, fn: (this: T, next: (err?: CallbackError) => void, docs: any | Array) => void | Promise): this;
pre(method: 'insertMany' | RegExp, options: SchemaPreOptions, fn: (this: T, next: (err?: CallbackError) => void, docs: any | Array) => void | Promise): this;
/** Object of currently defined query helpers on this schema. */
query: TQueryHelpers;
/** Adds a method call to the queue. */
queue(name: string, args: any[]): this;
/** Removes the given `path` (or [`paths`]). */
remove(paths: string | Array): this;
/** Removes index by name or index spec */
remove(index: string | AnyObject): this;
/** Returns an Array of path strings that are required by this schema. */
requiredPaths(invalidate?: boolean): string[];
/** Sets a schema option. */
set(key: K, value: SchemaOptions[K], _tags?: any): this;
/** Adds static "class" methods to Models compiled from this schema. */
static(name: K, fn: TStaticMethods[K]): this;
static(obj: { [F in keyof TStaticMethods]: TStaticMethods[F] } & { [name: string]: (this: M, ...args: any[]) => any }): this;
static(name: string, fn: (this: M, ...args: any[]) => any): this;
/** Object of currently defined statics on this schema. */
statics: { [F in keyof TStaticMethods]: TStaticMethods[F] } & { [name: string]: (this: M, ...args: any[]) => any };
/** Creates a virtual type with the given name. */
virtual>(
name: keyof TVirtuals | string,
options?: VirtualTypeOptions
): VirtualType;
/** Object of currently defined virtuals on this schema */
virtuals: TVirtuals;
/** Returns the virtual type with the given `name`. */
virtualpath>(name: string): VirtualType | null;
}
export type NumberSchemaDefinition = typeof Number | 'number' | 'Number' | typeof Schema.Types.Number;
export type StringSchemaDefinition = typeof String | 'string' | 'String' | typeof Schema.Types.String;
export type BooleanSchemaDefinition = typeof Boolean | 'boolean' | 'Boolean' | typeof Schema.Types.Boolean;
export type DateSchemaDefinition = typeof NativeDate | 'date' | 'Date' | typeof Schema.Types.Date;
export type ObjectIdSchemaDefinition = 'ObjectId' | 'ObjectID' | typeof Schema.Types.ObjectId;
export type SchemaDefinitionWithBuiltInClass = T extends number
? NumberSchemaDefinition
: T extends string
? StringSchemaDefinition
: T extends boolean
? BooleanSchemaDefinition
: T extends NativeDate
? DateSchemaDefinition
: (Function | string);
export type SchemaDefinitionProperty = SchemaDefinitionWithBuiltInClass |
SchemaTypeOptions |
typeof SchemaType |
Schema |
Schema[] |
SchemaTypeOptions>[] |
Function[] |
SchemaDefinition |
SchemaDefinition>[] |
typeof Schema.Types.Mixed |
MixedSchemaTypeOptions;
export type SchemaDefinition = T extends undefined
? { [path: string]: SchemaDefinitionProperty; }
: { [path in keyof T]?: SchemaDefinitionProperty; };
export type AnyArray = T[] | ReadonlyArray;
export type ExtractMongooseArray = T extends Types.Array ? AnyArray> : T;
export interface MixedSchemaTypeOptions extends SchemaTypeOptions {
type: typeof Schema.Types.Mixed;
}
export type RefType =
| number
| string
| Buffer
| undefined
| Types.ObjectId
| Types.Buffer
| typeof Schema.Types.Number
| typeof Schema.Types.String
| typeof Schema.Types.Buffer
| typeof Schema.Types.ObjectId;
export type InferId = T extends { _id?: any } ? T['_id'] : Types.ObjectId;
export interface VirtualTypeOptions {
/** If `ref` is not nullish, this becomes a populated virtual. */
ref?: string | Function;
/** The local field to populate on if this is a populated virtual. */
localField?: string | ((this: HydratedDocType, doc: HydratedDocType) => string);
/** The foreign field to populate on if this is a populated virtual. */
foreignField?: string | ((this: HydratedDocType, doc: HydratedDocType) => string);
/**
* By default, a populated virtual is an array. If you set `justOne`,
* the populated virtual will be a single doc or `null`.
*/
justOne?: boolean;
/** If you set this to `true`, Mongoose will call any custom getters you defined on this virtual. */
getters?: boolean;
/**
* If you set this to `true`, `populate()` will set this virtual to the number of populated
* documents, as opposed to the documents themselves, using `Query#countDocuments()`.
*/
count?: boolean;
/** Add an extra match condition to `populate()`. */
match?: FilterQuery | Function;
/** Add a default `limit` to the `populate()` query. */
limit?: number;
/** Add a default `skip` to the `populate()` query. */
skip?: number;
/**
* For legacy reasons, `limit` with `populate()` may give incorrect results because it only
* executes a single query for every document being populated. If you set `perDocumentLimit`,
* Mongoose will ensure correct `limit` per document by executing a separate query for each
* document to `populate()`. For example, `.find().populate({ path: 'test', perDocumentLimit: 2 })`
* will execute 2 additional queries if `.find()` returns 2 documents.
*/
perDocumentLimit?: number;
/** Additional options like `limit` and `lean`. */
options?: QueryOptions & { match?: AnyObject };
/** Additional options for plugins */
[extra: string]: any;
}
export class VirtualType {
/** Applies getters to `value`. */
applyGetters(value: any, doc: Document): any;
/** Applies setters to `value`. */
applySetters(value: any, doc: Document): any;
/** Adds a custom getter to this virtual. */
get(fn: (this: T, value: any, virtualType: VirtualType, doc: T) => any): this;
/** Adds a custom setter to this virtual. */
set(fn: (this: T, value: any, virtualType: VirtualType, doc: T) => void): this;
}
export type ReturnsNewDoc = { new: true } | { returnOriginal: false } | { returnDocument: 'after' };
export type ProjectionElementType = number | string;
export type ProjectionType = { [P in keyof T]?: ProjectionElementType } | AnyObject | string;
export type SortValues = SortOrder;
export type SortOrder = -1 | 1 | 'asc' | 'ascending' | 'desc' | 'descending';
type _UpdateQuery = {
/** @see https://docs.mongodb.com/manual/reference/operator/update-field/ */
$currentDate?: AnyKeys & AnyObject;
$inc?: AnyKeys & AnyObject;
$min?: AnyKeys & AnyObject;
$max?: AnyKeys & AnyObject;
$mul?: AnyKeys & AnyObject;
$rename?: Record;
$set?: AnyKeys & AnyObject;
$setOnInsert?: AnyKeys & AnyObject;
$unset?: AnyKeys & AnyObject;
/** @see https://docs.mongodb.com/manual/reference/operator/update-array/ */
$addToSet?: AnyKeys & AnyObject;
$pop?: AnyKeys & AnyObject;
$pull?: AnyKeys & AnyObject;
$push?: AnyKeys & AnyObject;
$pullAll?: AnyKeys & AnyObject;
/** @see https://docs.mongodb.com/manual/reference/operator/update-bitwise/ */
$bit?: Record;
};
export type UpdateWithAggregationPipeline = UpdateAggregationStage[];
export type UpdateAggregationStage = { $addFields: any } |
{ $set: any } |
{ $project: any } |
{ $unset: any } |
{ $replaceRoot: any } |
{ $replaceWith: any };
/**
* Update query command to perform on the document
* @example
* ```js
* { age: 30 }
* ```
*/
export type UpdateQuery = _UpdateQuery & AnyObject;
export type DocumentDefinition = {
[K in keyof Omit>]:
[Extract] extends [never]
? T[K] extends TreatAsPrimitives
? T[K]
: LeanDocumentElement
: T[K] | string;
};
export type FlattenMaps = {
[K in keyof T]: T[K] extends Map
? AnyObject : T[K] extends TreatAsPrimitives
? T[K] : FlattenMaps;
};
export type actualPrimitives = string | boolean | number | bigint | symbol | null | undefined;
export type TreatAsPrimitives = actualPrimitives | NativeDate | RegExp | symbol | Error | BigInt | Types.ObjectId;
export type LeanType =
0 extends (1 & T) ? T : // any
T extends TreatAsPrimitives ? T : // primitives
T extends Types.Subdocument ? Omit, '$isSingleNested' | 'ownerDocument' | 'parent'> :
LeanDocument; // Documents and everything else
export type LeanArray = T extends unknown[][] ? LeanArray[] : LeanType[];
export type _LeanDocument = {
[K in keyof T]: LeanDocumentElement;
};
// Keep this a separate type, to ensure that T is a naked type.
// This way, the conditional type is distributive over union types.
// This is required for PopulatedDoc.
export type LeanDocumentElement =
T extends unknown[] ? LeanArray : // Array
T extends Document ? LeanDocument : // Subdocument
T;
export type SchemaDefinitionType = T extends Document ? Omit> : T;
// Helpers to simplify checks
type IfAny = 0 extends (1 & IFTYPE) ? THENTYPE : ELSETYPE;
type IfUnknown = unknown extends IFTYPE ? THENTYPE : IFTYPE;
// tests for these two types are located in test/types/lean.test.ts
export type DocTypeFromUnion = T extends (Document & infer U) ?
[U] extends [Document & infer U] ? IfUnknown, false> : false : false;
export type DocTypeFromGeneric = T extends Document ?
IfUnknown, false> : false;
/**
* Helper to choose the best option between two type helpers
*/
export type _pickObject = T1 extends false ? T2 extends false ? Fallback : T2 : T1;
/**
* There may be a better way to do this, but the goal is to return the DocType if it can be infered
* and if not to return a type which is easily identified as "not valid" so we fall back to
* "strip out known things added by extending Document"
* There are three basic ways to mix in Document -- "Document & T", "Document",
* and "T extends Document". In the last case there is no type without Document mixins, so we can only
* strip things out. In the other two cases we can infer the type, so we should
*/
export type BaseDocumentType = _pickObject, DocTypeFromGeneric, false>;
/**
* Documents returned from queries with the lean option enabled.
* Plain old JavaScript object documents (POJO).
* @see https://mongoosejs.com/docs/tutorials/lean.html
*/
export type LeanDocument = Omit<_LeanDocument, Exclude | '$isSingleNested'>;
export type LeanDocumentOrArray = 0 extends (1 & T) ? T :
T extends unknown[] ? LeanDocument[] :
T extends Document ? LeanDocument :
T;
export type LeanDocumentOrArrayWithRawType = 0 extends (1 & T) ? T :
T extends unknown[] ? LeanDocument[] :
T extends Document ? LeanDocument :
T;
/* for ts-mongoose */
export class mquery { }
export default mongoose;
}