@typegoose/typegoose
- Version 9.9.0
- Published
- 232 kB
- 5 dependencies
- MIT license
Install
npm i @typegoose/typegoose
yarn add @typegoose/typegoose
pnpm add @typegoose/typegoose
Overview
Define Mongoose models using TypeScript classes
Index
Variables
Functions
- addModelToTypegoose()
- buildSchema()
- deleteModel()
- deleteModelWithClass()
- getClass()
- getClassForDocument()
- getDiscriminatorModelForClass()
- getModelForClass()
- getModelWithString()
- getName()
- index()
- Index()
- isDocument()
- isDocumentArray()
- isModel()
- isRefType()
- isRefTypeArray()
- modelOptions()
- ModelOptions()
- plugin()
- Plugins()
- prop()
- Prop()
- queryMethod()
- QueryMethod()
- setGlobalOptions()
- setLogLevel()
Classes
Enums
Type Aliases
Namespaces
errors
- AssertionFallbackError
- CannotBeSymbolError
- ExpectedTypeError
- FunctionCalledMoreThanSupportedError
- InvalidEnumTypeError
- InvalidOptionsConstructorError
- InvalidPropTypeError
- InvalidTypeError
- InvalidWhatIsItError
- NoDiscriminatorFunctionError
- NotAllVPOPElementsError
- NotNumberTypeError
- NotStringTypeError
- NotValidModelError
- NoValidClassError
- OptionDoesNotSupportOptionError
- PathNotInSchemaError
- RefOptionIsUndefinedError
- ResolveTypegooseNameError
- SelfContainingClassError
- StringLengthExpectedError
types
- AnyParamConstructor
- ArrayPropOptions
- AsQueryMethod
- BasePropOptions
- BeAnObject
- CustomNameFunction
- DecoratedPropertyMetadata
- DecoratedPropertyMetadataMap
- DeferredFunc
- DiscriminatorObject
- DocumentType
- DynamicStringFunc
- EmptyVoidFn
- Func
- GetTypeReturn
- HookOptionsEither
- ICustomOptions
- IGlobalOptions
- IHooksArray
- IIndexArray
- IModelOptions
- IndexOptions
- InnerOuterOptions
- IObjectWithTypegooseFunction
- IObjectWithTypegooseName
- IPluginsArray
- IPrototype
- KeyStringAny
- MapPropOptions
- ModelType
- NestedDiscriminatorsMap
- PropOptionsForNumber
- PropOptionsForString
- QueryHelperThis
- QueryMethodMap
- Ref
- RefType
- ReturnModelType
- TransformStringOptions
- ValidateNumberOptions
- ValidateStringOptions
- VirtualOptions
- VirtualPopulateMap
Variables
variable LogLevels
const LogLevels: logger.LogLevel;
variable post
const post: { <T>( method: RegExp, fn: PostRegExpResponse<T>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_1>( method: RegExp, fn: PostRegExpWithError<T_1>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_2>( method: NumberMethod, fn: PostNumberResponse<T_2>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_3>( method: NumberMethod, fn: PostNumberWithError<T_3>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_4>( method: SingleMethod, fn: PostSingleResponse<T_4>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_5>( method: SingleMethod, fn: PostSingleWithError<T_5>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_6>( method: MultipleMethod, fn: PostMultipleResponse<T_6>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_7>( method: MultipleMethod, fn: PostMultipleWithError<T_7>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_8>( method: ModelMethod, fn: ModelPostFn<T_8> | PostMultipleResponse<T_8>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_9>( method: DocumentMethod | DocumentMethod[], fn: PostArrayResponse<T_9>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_10>( method: DocumentMethod | DocumentMethod[], fn: PostArrayWithError<T_10>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_11>( method: QMR | QMR[], fn: PostQueryArrayResponse<T_11>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_12>( method: QMR | QMR[], fn: PostQueryArrayWithError<T_12>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator;};
variable Post
const Post: { <T>( method: RegExp, fn: PostRegExpResponse<T>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_1>( method: RegExp, fn: PostRegExpWithError<T_1>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_2>( method: NumberMethod, fn: PostNumberResponse<T_2>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_3>( method: NumberMethod, fn: PostNumberWithError<T_3>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_4>( method: SingleMethod, fn: PostSingleResponse<T_4>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_5>( method: SingleMethod, fn: PostSingleWithError<T_5>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_6>( method: MultipleMethod, fn: PostMultipleResponse<T_6>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_7>( method: MultipleMethod, fn: PostMultipleWithError<T_7>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_8>( method: ModelMethod, fn: ModelPostFn<T_8> | PostMultipleResponse<T_8>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_9>( method: DocumentMethod | DocumentMethod[], fn: PostArrayResponse<T_9>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_10>( method: DocumentMethod | DocumentMethod[], fn: PostArrayWithError<T_10>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_11>( method: QMR | QMR[], fn: PostQueryArrayResponse<T_11>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_12>( method: QMR | QMR[], fn: PostQueryArrayWithError<T_12>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator;};
variable pre
const pre: { <T>( method: AggregateMethod, fn: PreFnWithAggregate<T>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_1>( method: DR | DR[], fn: PreFnWithDocumentType<T_1>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_2>( method: QMR | QMR[], fn: PreFnWithQuery<T_2>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator;};
variable Pre
const Pre: { <T>( method: AggregateMethod, fn: PreFnWithAggregate<T>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_1>( method: DR | DR[], fn: PreFnWithDocumentType<T_1>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator; <T_2>( method: QMR | QMR[], fn: PreFnWithQuery<T_2>, options?: mongoose.MiddlewareOptions | undefined ): ClassDecorator;};
Functions
function addModelToTypegoose
addModelToTypegoose: < U extends AnyParamConstructor<any>, QueryHelpers = BeAnObject>( model: mongoose.Model<any>, cl: U, options?: { existingMongoose?: mongoose.Mongoose; existingConnection?: any }) => ReturnModelType<U, QueryHelpers>;
Add a Class-Model Pair to the Typegoose Cache This can be used to add custom Models to Typegoose, with the type information of "cl" Note: no gurantee that the type information is fully correct when used manually
Parameter model
The Model to store
Parameter cl
The Class to store
Parameter options
Overwrite existingMongoose or existingConnection
Example 1
class ClassName {}const schema = buildSchema(ClassName);// modifications to the schame can be doneconst model = addModelToTypegoose(mongoose.model("Name", schema), ClassName);
function buildSchema
buildSchema: <U extends AnyParamConstructor<any>>( cl: U, options?: mongoose.SchemaOptions, overwriteOptions?: IModelOptions) => mongoose.Schema<DocumentType<InstanceType<U>, BeAnObject>>;
Generates a Mongoose schema out of class props, iterating through all parents
Parameter cl
The Class to build a Schema from
Parameter options
Overwrite SchemaOptions (Merged with Decorator)
Parameter overwriteOptions
Overwrite ModelOptions (aside from schemaOptions) (Not Merged with Decorator)
Returns
Returns the Build Schema
Example 1
class ClassName {}const NameSchema = buildSchema(ClassName);const NameModel = mongoose.model("Name", NameSchema);
function deleteModel
deleteModel: (name: string) => void;
Deletes a existing model so that it can be overwritten with another model (deletes from mongoose.connection and typegoose models cache and typegoose constructors cache)
Parameter name
The Model's mongoose name
Example 1
class ClassName {}const NameModel = getModelForClass(ClassName);deleteModel("ClassName");
function deleteModelWithClass
deleteModelWithClass: <U extends AnyParamConstructor<any>>(cl: U) => void;
Delete a model, with the given class Same as "deleteModel", only that it can be done with the class instead of the name
Parameter cl
The Class to delete the model from
Example 1
class ClassName {}const NameModel = getModelForClass(ClassName);deleteModelWithClass(ClassName);
function getClass
getClass: ( input: | (mongoose.Document & IObjectWithTypegooseFunction) | (mongoose.Schema.Types.Subdocument & IObjectWithTypegooseFunction) | string | IObjectWithTypegooseName | any) => NewableFunction | undefined;
Get the Class for a given Schema
Parameter input
The Input to fetch the class from
function getClassForDocument
getClassForDocument: ( document: mongoose.Document) => NewableFunction | undefined;
Get the Class for a given Document
Parameter document
The Document to fetch the class from
function getDiscriminatorModelForClass
getDiscriminatorModelForClass: { <U extends AnyParamConstructor<any>, QueryHelpers = BeAnObject>( from: mongoose.Model<any, any>, cl: U, options?: IModelOptions ): ReturnModelType<U, QueryHelpers>; <U extends AnyParamConstructor<any>, QueryHelpers = BeAnObject>( from: mongoose.Model<any, any>, cl: U, value?: string ): any; <U extends AnyParamConstructor<any>, QueryHelpers = BeAnObject>( from: mongoose.Model<any, any>, cl: U, value?: string, options?: IModelOptions ): any;};
Build a Model from the given Class and add it as a discriminator onto "from"
Parameter from
The Model to add the new discriminator model to
Parameter cl
The Class to make a discriminator model from
Parameter options
Overwrite ModelOptions (Merged with ModelOptions from class)
Example 1
class Main {@prop({ ref: () => BaseDiscriminator })public discriminators?: Ref<BaseDiscriminator>;}class BaseDiscriminator {@prop()public propertyOnAllDiscriminators?: string;}class AnotherDiscriminator {@prop()public someValue?: string;}const MainModel = getModelForClass(Main);const BaseDiscriminatorModel = getModelFroClass(BaseDiscriminator);const AnotherDiscriminatorModel = getDiscriminatorModelForClass(BaseDiscriminatorModel, AnotherDiscriminator);// add other discriminator models the same way as "AnotherDiscriminatorModel"Build a Model from the given Class and add it as a discriminator onto "from"
Parameter from
The Model to add the new discriminator model to
Parameter cl
The Class to make a discriminator model from
Parameter value
The Identifier to use to differentiate documents (default: cl.name)
Example 1
class Main {@prop({ ref: () => BaseDiscriminator })public discriminators?: Ref<BaseDiscriminator>;}class BaseDiscriminator {@prop()public propertyOnAllDiscriminators?: string;}class AnotherDiscriminator {@prop()public someValue?: string;}const MainModel = getModelForClass(Main);const BaseDiscriminatorModel = getModelFroClass(BaseDiscriminator);const AnotherDiscriminatorModel = getDiscriminatorModelForClass(BaseDiscriminatorModel, AnotherDiscriminator);// add other discriminator models the same way as "AnotherDiscriminatorModel"Build a Model from the given Class and add it as a discriminator onto "from"
Parameter from
The Model to add the new discriminator model to
Parameter cl
The Class to make a discriminator model from
Parameter value
The Identifier to use to differentiate documents (default: cl.name)
Parameter options
Overwrite ModelOptions (Merged with ModelOptions from class)
Example 1
class Main {@prop({ ref: () => BaseDiscriminator })public discriminators?: Ref<BaseDiscriminator>;}class BaseDiscriminator {@prop()public propertyOnAllDiscriminators?: string;}class AnotherDiscriminator {@prop()public someValue?: string;}const MainModel = getModelForClass(Main);const BaseDiscriminatorModel = getModelFroClass(BaseDiscriminator);const AnotherDiscriminatorModel = getDiscriminatorModelForClass(BaseDiscriminatorModel, AnotherDiscriminator);// add other discriminator models the same way as "AnotherDiscriminatorModel"
function getModelForClass
getModelForClass: < U extends AnyParamConstructor<any>, QueryHelpers = BeAnObject>( cl: U, options?: IModelOptions) => ReturnModelType<U, QueryHelpers>;
Build a Model From a Class
Parameter cl
The Class to build a Model from
Parameter options
Overwrite SchemaOptions (Merged with Decorator)
Returns
The finished Model
Example 1
class ClassName {}const NameModel = getModelForClass(ClassName);Modifiers
@public
function getModelWithString
getModelWithString: <U extends AnyParamConstructor<any>>( key: string) => undefined | ReturnModelType<U>;
Get Model from internal cache
Parameter key
Model's name key
Example 1
class ClassName {}getModelForClass(ClassName); // build the modelconst NameModel = getModelWithString<typeof ClassName>("ClassName");
function getName
getName: <U extends AnyParamConstructor<any>>( cl: U, overwriteOptions?: IModelOptions) => string;
Get the Class's final name (combines all available options to generate a name)
Parameter cl
The Class to get the name for
Parameter overwriteOptions
Overwrite ModelOptions to generate a name from (Only name related options are merged)
function index
index: <T extends BeAnObject = BeAnObject>( fields: Partial<Record<keyof T, string | -1 | 1>>, options?: IndexOptions<T>) => ClassDecorator;
Defines a index for this Class which will then be added to the Schema.
Parameter fields
Which fields to index (if multiple fields are set, it will be a compound index)
Parameter options
Options to pass to MongoDB driver's createIndex() function
Example 1
Example:
@index({ article: 1, user: 1 }, { unique: true })class ClassName {}
function Index
Index: <T extends BeAnObject = BeAnObject>( fields: Partial<Record<keyof T, string | -1 | 1>>, options?: IndexOptions<T>) => ClassDecorator;
Defines a index for this Class which will then be added to the Schema.
Parameter fields
Which fields to index (if multiple fields are set, it will be a compound index)
Parameter options
Options to pass to MongoDB driver's createIndex() function
Example 1
Example:
@index({ article: 1, user: 1 }, { unique: true })class ClassName {}
function isDocument
isDocument: <T, S extends mongoose.RefType>( doc: mongoose.PopulatedDoc<PopulatedType, RawId>) => doc is DocumentType<T, BeAnObject>;
Check if the given document is populated
Parameter doc
The Ref with uncertain type
function isDocumentArray
isDocumentArray: { <T, S extends mongoose.RefType>( docs: mongoose.Types.Array<Ref<T, S>> | undefined ): docs is mongoose.Types.Array<DocumentType<NonNullable<T>, BeAnObject>>; <T, S extends mongoose.RefType>( docs: mongoose.PopulatedDoc<PopulatedType, RawId>[] ): docs is DocumentType<NonNullable<T>, BeAnObject>[];};
Check if the given array is fully populated Only returns "true" if all members in the array are populated
Parameter docs
The Array of Refs with uncertain type
function isModel
isModel: (model: any) => model is mongoose.Model<any>;
Check if the input is a mongoose.Model
Parameter model
The Value to check
function isRefType
isRefType: <T, S extends mongoose.RefType>( doc: Ref<T, S> | undefined, refType: AllowedRefTypes) => doc is NonNullable<S>;
Check if the document is of type "refType"
Parameter doc
The Ref with uncretain type
function isRefTypeArray
isRefTypeArray: { <T, S extends mongoose.RefType>( docs: mongoose.Types.Array<Ref<T, S>> | undefined, refType: AllowedRefTypes ): docs is mongoose.Types.Array<NonNullable<S>>; <T, S extends mongoose.RefType>( docs: mongoose.PopulatedDoc<PopulatedType, RawId>[], refType: any ): docs is NonNullable<S>[];};
Check if the array is fully of type "refType" Only returns "true" if all members in the array are of type "refType"
Parameter docs
The Ref with uncretain type
function modelOptions
modelOptions: (options: IModelOptions) => ClassDecorator;
Define Options for the Class
Parameter options
The Options to set
Example 1
Example:
@modelOptions({ schemaOptions: { timestamps: true } })class ClassName {}// The default Class "TimeStamps" can be used for type information and options already set
function ModelOptions
ModelOptions: (options: IModelOptions) => ClassDecorator;
Define Options for the Class
Parameter options
The Options to set
Example 1
Example:
@modelOptions({ schemaOptions: { timestamps: true } })class ClassName {}// The default Class "TimeStamps" can be used for type information and options already set
function plugin
plugin: <TFunc extends Func, TParams = Parameters<TFunc>[1]>( mongoosePlugin: TFunc, options?: TParams) => ClassDecorator;
Add a mongoose Middleware-Plugin
Parameter mongoosePlugin
The Plugin to plug-in
Parameter options
Options for the Plugin, if any
Example 1
Example:
@plugin(findOrCreate, { optionsHere: true })class ClassName {}
function Plugins
Plugins: <TFunc extends Func, TParams = Parameters<TFunc>[1]>( mongoosePlugin: TFunc, options?: TParams) => ClassDecorator;
Add a mongoose Middleware-Plugin
Parameter mongoosePlugin
The Plugin to plug-in
Parameter options
Options for the Plugin, if any
Example 1
Example:
@plugin(findOrCreate, { optionsHere: true })class ClassName {}
function prop
prop: ( options?: | BasePropOptions | ArrayPropOptions | MapPropOptions | PropOptionsForNumber | PropOptionsForString | VirtualOptions, kind?: PropType) => PropertyDecorator;
Set Property Options for the property below
Parameter options
The Options to Set
Parameter kind
Overwrite auto-inferred PropType
Example 1
class ClassName {@prop()public someProp?: string;@prop({ type: () => [String] })public someArrayProp?: string[];@prop({ type: () => String })public someMapProp?: Map<string, string>;}
function Prop
Prop: ( options?: | BasePropOptions | ArrayPropOptions | MapPropOptions | PropOptionsForNumber | PropOptionsForString | VirtualOptions, kind?: PropType) => PropertyDecorator;
Set Property Options for the property below
Parameter options
The Options to Set
Parameter kind
Overwrite auto-inferred PropType
Example 1
class ClassName {@prop()public someProp?: string;@prop({ type: () => [String] })public someArrayProp?: string[];@prop({ type: () => String })public someMapProp?: Map<string, string>;}
function queryMethod
queryMethod: <QueryHelpers, U extends AnyParamConstructor<any>>( func: ( this: mongoose.QueryWithHelpers<S, S, QueryHelpers>, ...params: any[] ) => Query<any, any>) => ClassDecorator;
Adds a query method to the Class which will then be added to the Schema.
Parameter func
The Query Method to add
Example 1
interface FindHelpers {findByTitle: AsQueryMethod<typeof findByTitle>;}function findByTitle(this: ReturnModelType<typeof Event, FindHelpers>, title: string) {return this.find({ title });}@queryMethod(findByTitle)class Event {@prop()public title: string;}const EventModel = getModelForClass<typeof Event, FindHelpers>(Event);
function QueryMethod
QueryMethod: <QueryHelpers, U extends AnyParamConstructor<any>>( func: ( this: mongoose.QueryWithHelpers<S, S, QueryHelpers>, ...params: any[] ) => Query<any, any>) => ClassDecorator;
Adds a query method to the Class which will then be added to the Schema.
Parameter func
The Query Method to add
Example 1
interface FindHelpers {findByTitle: AsQueryMethod<typeof findByTitle>;}function findByTitle(this: ReturnModelType<typeof Event, FindHelpers>, title: string) {return this.find({ title });}@queryMethod(findByTitle)class Event {@prop()public title: string;}const EventModel = getModelForClass<typeof Event, FindHelpers>(Event);
function setGlobalOptions
setGlobalOptions: (options: IGlobalOptions) => void;
Set Typegoose's global Options
function setLogLevel
setLogLevel: (level: logger.LogLevelDesc, persist?: boolean | undefined) => void;
Classes
class Passthrough
class Passthrough {}
Use this class if raw mongoose for a path is wanted It is still recommended to use the typegoose classes directly
Example 1
class Dummy {@prop({ type: () => new Passthrough({ somePath: String }) })public somepath: { somePath: string };}class Dummy {@prop({ type: () => new Passthrough({ somePath: String }, true) })public somepath: { somePath: string };}See Also
Using
Passthrough
, the paths created will also result as anSchema
(since mongoose 6.0), see
constructor
constructor(raw: any, direct?: boolean);
Use this like
new mongoose.Schema()
Parameter raw
The Schema definition
Parameter direct
Directly insert "raw", instead of using "type" (this will not apply any other inner options)
property direct
direct: boolean;
property raw
raw: any;
Enums
enum PropType
enum PropType { ARRAY = 0, MAP = 1, NONE = 2,}
This Enum is meant for baseProp to decide for diffrent props (like if it is an arrayProp or prop or mapProp)
Type Aliases
type DocumentType
type DocumentType<T, QueryHelpers = BeAnObject> = (T extends { _id: unknown;} ? mongoose.Document<T['_id'], QueryHelpers> & T : mongoose.Document<any, QueryHelpers> & T) & IObjectWithTypegooseFunction;
Get the Type of an instance of a Document with Class properties
Example 1
class ClassName {}const NameModel = getModelForClass(ClassName);const doc: DocumentType<ClassName> = await NameModel.create({});
type Ref
type Ref< PopulatedType, RawId extends mongoose.RefType = | (PopulatedType extends { _id?: mongoose.RefType; } ? NonNullable<PopulatedType['_id']> : mongoose.Types.ObjectId) | undefined> = mongoose.PopulatedDoc<PopulatedType, RawId>;
Reference another Model
type ReturnModelType
type ReturnModelType< U extends AnyParamConstructor<any>, QueryHelpers = BeAnObject> = ModelType<InstanceType<U>, QueryHelpers> & U;
The Type of a Model that gets returned by "getModelForClass" and "setModelForClass"
Namespaces
namespace defaultClasses
module 'lib/defaultClasses.d.ts' {}
This Interface can be used when "_id" and "id" need to be defined in types
class FindOrCreate
abstract class FindOrCreate {}
This class contains all types for the module "mongoose-findorcreate"
property findOrCreate
static findOrCreate: <T extends FindOrCreate>( this: AnyParamConstructor<T>, condition: any, createWith?: any) => Promise<FindOrCreateResult<T>>;
class TimeStamps
abstract class TimeStamps {}
interface Base
interface Base<IDType extends RefType = Types.ObjectId> {}
This Interface can be used when "_id" and "id" need to be defined in types
property id
id: string;
This getter/setter dosnt exist if "schemaOptions.id" being set to "false"
interface FindOrCreateResult
interface FindOrCreateResult<T> {}
namespace errors
module 'lib/internal/errors.d.ts' {}
Not All Virtual Populate Elements Error
variable InvalidWhatIsItError
const InvalidWhatIsItError: typeof InvalidPropTypeError;
Deprecated
This was renamed to "InvalidPropTypeError" and will be removed in 10.0
class AssertionFallbackError
class AssertionFallbackError extends Error {}
constructor
constructor();
class CannotBeSymbolError
class CannotBeSymbolError extends Error {}
constructor
constructor(name: string, key: string | symbol);
class ExpectedTypeError
class ExpectedTypeError extends TypeError {}
constructor
constructor(optionName: string, expected: string, got: {});
class FunctionCalledMoreThanSupportedError
class FunctionCalledMoreThanSupportedError extends Error {}
constructor
constructor(functionName: string, supported: number, extra: string);
class InvalidEnumTypeError
class InvalidEnumTypeError extends TypeError {}
constructor
constructor(name: string, key: string, value: {});
class InvalidOptionsConstructorError
class InvalidOptionsConstructorError extends TypeError {}
constructor
constructor(name: string, key: string, type: {});
class InvalidPropTypeError
class InvalidPropTypeError extends Error {}
Error for when an unknown PropType is passed to an switch, gets thrown in the default case
constructor
constructor(proptype: {}, name: string, key: string, where: string);
class InvalidTypeError
class InvalidTypeError extends Error {}
constructor
constructor(targetName: string, key: string, Type: {});
class NoDiscriminatorFunctionError
class NoDiscriminatorFunctionError extends Error {}
constructor
constructor(name: string, key: string);
class NotAllVPOPElementsError
class NotAllVPOPElementsError extends Error {}
Not All Virtual Populate Elements Error
constructor
constructor(name: string, key: string);
class NotNumberTypeError
class NotNumberTypeError extends Error {}
constructor
constructor(targetName: string, key: string, enumKey: string, enumValue: string);
class NotStringTypeError
class NotStringTypeError extends Error {}
constructor
constructor(targetName: string, key: string, enumKey: string, enumValue: string);
class NotValidModelError
class NotValidModelError extends TypeError {}
constructor
constructor(model: {}, where: string);
class NoValidClassError
class NoValidClassError extends TypeError {}
constructor
constructor(value: {});
class OptionDoesNotSupportOptionError
class OptionDoesNotSupportOptionError extends TypeError {}
constructor
constructor( currentOption: string, problemOption: string, expected: string, provided: string);
class PathNotInSchemaError
class PathNotInSchemaError extends Error {}
constructor
constructor(name: string, key: string);
class RefOptionIsUndefinedError
class RefOptionIsUndefinedError extends Error {}
constructor
constructor(name: string, key: string);
class ResolveTypegooseNameError
class ResolveTypegooseNameError extends ReferenceError {}
constructor
constructor(input: {});
class SelfContainingClassError
class SelfContainingClassError extends TypeError {}
constructor
constructor(name: string, key: string);
class StringLengthExpectedError
class StringLengthExpectedError extends TypeError {}
constructor
constructor(length: number, got: any, where: string, valueName: string);
namespace types
module 'lib/types.d.ts' {}
Get the Type of an instance of a Document with Class properties
Example 1
class ClassName {}const NameModel = getModelForClass(ClassName);const doc: DocumentType<ClassName> = await NameModel.create({});
interface ArrayPropOptions
interface ArrayPropOptions extends BasePropOptions, InnerOuterOptions {}
Options for Array's
property castNonArrays
castNonArrays?: boolean;
Set if Non-Array values will be cast to an array
NOTE: This option currently only really affects "DocumentArray" and not normal arrays, https://github.com/Automattic/mongoose/issues/10398
Example 1
new Model({ array: "string" });// will be cast to equalnew Model({ array: ["string"] });true
See Also
https://mongoosejs.com/docs/api/schemaarray.html#schemaarray_SchemaArray.options
property dim
dim?: number;
How many dimensions this Array should have (needs to be higher than 0)
Note: Custom Typegoose Option 1
interface BasePropOptions
interface BasePropOptions {}
This Interface for most properties uses "mongoose.SchemaTypeOptions['']", but for some special (or typegoose custom) options, it is not used
Example:
index
is directly from mongoose, where astype
is from typegoose
property addNullToEnum
addNullToEnum?: boolean;
Add "null" to the enum array Note: Custom Typegoose Option
property alias
alias?: mongoose.SchemaTypeOptions<any>['alias'];
Give the Property an alias in the output
Note: you should include the alias as a variable in the class, but not with a prop decorator
Example 1
class Dummy {@prop({ alias: "helloWorld" })public hello: string; // normal, with @proppublic helloWorld: string; // is just for type Completion, will not be included in the DB}
property auto
auto?: mongoose.SchemaTypeOptions<any>['auto'];
If true, uses Mongoose's default
_id
settings. Only allowed for ObjectIdsNote: Copied from mongoose's "index.d.ts"#SchemaTypeOptions
property autopopulate
autopopulate?: boolean | Function | KeyStringAny;
This option as only an effect when the plugin
mongoose-autopopulate
is used
property default
default?: mongoose.SchemaTypeOptions<any>['default'];
Give the Property a default Value
property discriminators
discriminators?: DeferredFunc< (AnyParamConstructor<any> | DiscriminatorObject)[]>;
Set the Nested Discriminators
Note: "_id: false" as an prop option dosnt work here
Note: Custom Typegoose Option
property enum
enum?: string[] | BeAnObject;
Only accept Values from the Enum(|Array)
property excludeIndexes
excludeIndexes?: mongoose.SchemaTypeOptions<any>['excludeIndexes'];
If
true
, Mongoose will skip gathering indexes on subpaths. Only allowed for subdocuments and subdocument arrays.Note: Copied from mongoose's "index.d.ts"#SchemaTypeOptions
property expires
expires?: mongoose.SchemaTypeOptions<any>['expires'];
Should this property have an "expires" index? https://docs.mongodb.com/manual/tutorial/expire-data
property get
get?: mongoose.SchemaTypeOptions<any>['get'];
Set a Getter (Non-Virtual) to Post-process your value (when using get/set both are required) Please note that the option
type
is required, if get/set saves a different value than what is definedParameter value
The Value that needs to get modified
Returns
The Value, but modified OR anything
Example 1
function setHello(val: string): string {return val.toLowerCase()}function getHello(val: string): string {return val.toUpperCase();}class Dummy {@prop({ set: setHello, get: getHello }) // many options can be used, like requiredpublic hello: string;}
property immutable
immutable?: mongoose.SchemaTypeOptions<any>['immutable'];
Make a property read-only
Example 1
class SomeClass {@prop({ immutable: true })public someprop: Readonly<string>;}
property index
index?: mongoose.SchemaTypeOptions<any>['index'];
Should this property have an index? Note: dont use this if you want to do an compound index https://docs.mongodb.com/manual/indexes
property of
of?: never;
Use option
See Also
https://typegoose.github.io/typegoose/docs/api/decorators/prop#map-options
https://typegoose.github.io/typegoose/docs/api/decorators/prop#proptype
property ref
ref?: | DeferredFunc<string | AnyParamConstructor<any> | DynamicStringFunc<any>> | string | AnyParamConstructor<any>;
Reference an other Document (you should use Ref as Prop type)
property refPath
refPath?: string;
Take the Path and try to resolve it to a Model
property required
required?: mongoose.SchemaTypeOptions<any>['required'];
is this value required? false (Implicitly)
property select
select?: mongoose.SchemaTypeOptions<any>['select'];
include this value? true (Implicitly)
property set
set?: mongoose.SchemaTypeOptions<any>['set'];
Set a Setter (Non-Virtual) to pre-process your value (when using get/set both are required) Please note that the option
type
is required, if get/set saves a different value than what is definedParameter value
The Value that needs to get modified
Returns
The Value, but modified OR anything
Example 1
function setHello(val: string): string {return val.toLowerCase()}function getHello(val: string): string {return val.toUpperCase();}class Dummy {@prop({ set: setHello, get: getHello }) // many options can be used, like requiredpublic hello: string;}
property sparse
sparse?: mongoose.SchemaTypeOptions<any>['sparse'];
Should this property have an "sparse" index? https://docs.mongodb.com/manual/indexes/#sparse-indexes
property subtype
subtype?: mongoose.SchemaTypeOptions<any>['subtype'];
The default [subtype](http://bsonspec.org/spec.html) associated with this buffer when it is stored in MongoDB. Only allowed for buffer paths
Note: Copied from mongoose's "index.d.ts"#SchemaTypeOptions
property text
text?: mongoose.SchemaTypeOptions<any>['text'];
Should this property have an "text" index? https://mongoosejs.com/docs/api.html#schematype_SchemaType-text
property transform
transform?: mongoose.SchemaTypeOptions<any>['transform'];
Define a transform function for this individual schema type. Only called when calling
toJSON()
ortoObject()
.Note: Copied from mongoose's "index.d.ts"#SchemaTypeOptions
property type
type?: DeferredFunc<AnyParamConstructor<any>> | DeferredFunc<unknown> | unknown;
This may be needed if get/set is used (this sets the type how it is saved to the DB)
property unique
unique?: mongoose.SchemaTypeOptions<any>['unique'];
Should this property have an "unique" index? https://docs.mongodb.com/manual/indexes/#unique-indexes
property validate
validate?: mongoose.SchemaTypeOptions<any>['validate'];
Give an Validator RegExp or Function
index signature
[extra: string]: any;
interface DecoratedPropertyMetadata
interface DecoratedPropertyMetadata {}
Type for the Values stored in the Reflection for Properties
interface DiscriminatorObject
interface DiscriminatorObject {}
interface GetTypeReturn
interface GetTypeReturn {}
The Return Type of "utils.getType"
interface ICustomOptions
interface ICustomOptions {}
Typegoose options, mostly for "modelOptions({ options: ICustomOptions })"
property allowMixed
allowMixed?: Severity;
Allow "mongoose.Schema.Types.Mixed"?
property automaticName
automaticName?: boolean;
Enable Automatic Name generation of a model Example: class with name of "SomeClass" and option "collection" of "SC"
will generate the name of "SomeClass_SC" false
property customName
customName?: string | CustomNameFunction;
Set the modelName of the class. If it is a function, the function will be executed. The function will override "automaticName". If "automaticName" is true and "customName" is a string, it sets a *suffix* instead of the whole name. schemaOptions.collection
property runSyncIndexes
runSyncIndexes?: boolean;
Run "model.syncIndexes" when model is finished compiling?
interface IGlobalOptions
interface IGlobalOptions {}
property globalOptions
globalOptions?: BeAnObject;
Global Options for general Typegoose (There are currently none)
property options
options?: ICustomOptions;
Typegoose Options
property schemaOptions
schemaOptions?: mongoose.SchemaOptions;
Schema Options that should get applied to all models
interface IHooksArray
interface IHooksArray {}
Type for the Values stored in the Reflection for Hooks
Example 1
const postHooks: IHooksArray[] = Array.from(Reflect.getMetadata(DecoratorKeys.HooksPost, target) ?? []);
interface IIndexArray
interface IIndexArray<T> {}
Type for the Values stored in the Reflection for Indexes
Example 1
const indices: IIndexArray[] = Reflect.getMetadata(DecoratorKeys.Index, target) || []);
interface IModelOptions
interface IModelOptions {}
property existingConnection
existingConnection?: mongoose.Connection;
An Existing Connection
property existingMongoose
existingMongoose?: mongoose.Mongoose;
An Existing Mongoose Connection
property options
options?: ICustomOptions;
Typegoose Custom Options
property schemaOptions
schemaOptions?: mongoose.SchemaOptions;
Supports all Mongoose's Schema Options
interface IndexOptions
interface IndexOptions<T> extends mongoose.IndexOptions {}
copy-paste from mongodb package (should be same as IndexOptions from 'mongodb')
property weights
weights?: Partial<Record<keyof T, number>>;
interface InnerOuterOptions
interface InnerOuterOptions {}
property innerOptions
innerOptions?: KeyStringAny;
Use this to define inner-options Use this if the auto-mapping is not correct or for plugin options
Please open a new issue if some option is mismatched or not existing / mapped
property outerOptions
outerOptions?: KeyStringAny;
Use this to define outer-options Use this if the auto-mapping is not correct or for plugin options
Please open a new issue if some option is mismatched or not existing / mapped
interface IObjectWithTypegooseFunction
interface IObjectWithTypegooseFunction {}
Interface describing a Object that has a "typegooseName" Function
method typegooseName
typegooseName: () => string;
interface IObjectWithTypegooseName
interface IObjectWithTypegooseName {}
Interface describing a Object that has a "typegooseName" Value
property typegooseName
typegooseName: string;
interface IPluginsArray
interface IPluginsArray<T> {}
Type for the Values stored in the Reflection for Plugins
Example 1
const plugins: IPluginsArray<any>[] = Array.from(Reflect.getMetadata(DecoratorKeys.Plugins, target) ?? []);
property mongoosePlugin
mongoosePlugin: Func;
property options
options: T;
interface IPrototype
interface IPrototype {}
For the types that error that seemingly dont have a prototype
property prototype
prototype?: any;
interface KeyStringAny
interface KeyStringAny {}
An Helper Interface for key: any: string
index signature
[key: string]: any;
interface MapPropOptions
interface MapPropOptions extends BasePropOptions, InnerOuterOptions {}
Options For Map's
interface TransformStringOptions
interface TransformStringOptions {}
property lowercase
lowercase?: mongoose.SchemaTypeOptions<any>['lowercase'];
Should it be lowercased before save?
property trim
trim?: mongoose.SchemaTypeOptions<any>['trim'];
Should it be trimmed before save?
property uppercase
uppercase?: mongoose.SchemaTypeOptions<any>['uppercase'];
Should it be uppercased before save?
interface ValidateNumberOptions
interface ValidateNumberOptions {}
interface ValidateStringOptions
interface ValidateStringOptions {}
property enum
enum?: string[];
Only allow Values from the enum
property match
match?: mongoose.SchemaTypeOptions<any>['match'];
Only allow values that match this RegExp
property maxlength
maxlength?: mongoose.SchemaTypeOptions<any>['maxlength'];
Only allow values that have at max this length
property minlength
minlength?: mongoose.SchemaTypeOptions<any>['minlength'];
Only allow values that have at least this length
interface VirtualOptions
interface VirtualOptions {}
property count
count?: mongoose.VirtualTypeOptions['count'];
Return the number of Documents found instead of the actual Documents
property foreignField
foreignField: mongoose.VirtualTypeOptions['foreignField'];
Which property(on the ref-Class) to match
localField
against
property getters
getters?: mongoose.VirtualTypeOptions['getters'];
If you set this to
true
, Mongoose will call any custom getters you defined on this virtual.Note: Copied from mongoose's "index.d.ts"#VirtualTypeOptions
property justOne
justOne?: mongoose.VirtualTypeOptions['justOne'];
Return as One Document(true) or as Array(false)
property limit
limit?: mongoose.VirtualTypeOptions['limit'];
Add a default
limit
to thepopulate()
query.Note: Copied from mongoose's "index.d.ts"#VirtualTypeOptions
property localField
localField: mongoose.VirtualTypeOptions['localField'];
Which property(on the current-Class) to match
foreignField
against
property match
match?: KeyStringAny | ((doc: any) => KeyStringAny);
Match Options
property options
options?: mongoose.VirtualTypeOptions['options'];
Extra Query Options
property perDocumentLimit
perDocumentLimit?: mongoose.VirtualTypeOptions['perDocumentLimit'];
For legacy reasons,
limit
withpopulate()
may give incorrect results because it only executes a single query for every document being populated. If you setperDocumentLimit
, Mongoose will ensure correctlimit
per document by executing a separate query for each document topopulate()
. For example,.find().populate({ path: 'test', perDocumentLimit: 2 })
will execute 2 additional queries if.find()
returns 2 documents.Note: Copied from mongoose's "index.d.ts"#VirtualTypeOptions
property ref
ref: NonNullable<BasePropOptions['ref']>;
Reference another Document (Ref should be used as property type)
property skip
skip?: mongoose.VirtualTypeOptions['skip'];
Add a default
skip
to thepopulate()
query.Note: Copied from mongoose's "index.d.ts"#VirtualTypeOptions
index signature
[extra: string]: any;
type AnyParamConstructor
type AnyParamConstructor<T> = new (...args: any) => T;
Any-param Constructor
type AsQueryMethod
type AsQueryMethod<T extends (...args: any) => any> = ( ...args: Parameters<T>) => ReturnType<T>;
Gets the signature (parameters with their types, and the return type) of a function type.
Should be used when defining an interface for a class that uses query methods.
Example 1
function sendMessage(recipient: string, sender: string, priority: number, retryIfFails: boolean) {// some logic...return true;}// Both of the following types will be identical.type SendMessageType = AsQueryMethod<typeof sendMessage>;type SendMessageManualType = (recipient: string, sender: string, priority: number, retryIfFails: boolean) => boolean;
type BeAnObject
type BeAnObject = Record<string, any>;
This type is for lint error "ban-types"
type CustomNameFunction
type CustomNameFunction = (options: IModelOptions) => string;
The Type of a function to generate a custom model name.
type DecoratedPropertyMetadataMap
type DecoratedPropertyMetadataMap = Map<string | symbol, DecoratedPropertyMetadata>;
type DeferredFunc
type DeferredFunc<T = any> = (...args: unknown[]) => T;
Defer an reference with an function (or as other projects call it "Forward declaration")
Parameter type
This is just to comply with the common pattern of
type => ActualType
type DocumentType
type DocumentType<T, QueryHelpers = BeAnObject> = (T extends { _id: unknown;} ? mongoose.Document<T['_id'], QueryHelpers> & T : mongoose.Document<any, QueryHelpers> & T) & IObjectWithTypegooseFunction;
Get the Type of an instance of a Document with Class properties
Example 1
class ClassName {}const NameModel = getModelForClass(ClassName);const doc: DocumentType<ClassName> = await NameModel.create({});
type DynamicStringFunc
type DynamicStringFunc<T extends AnyParamConstructor<any>> = ( doc: DocumentType<T>) => string;
Dynamic Functions, since mongoose 4.13
Parameter doc
The Document current document
type EmptyVoidFn
type EmptyVoidFn = () => void;
An Function type for a function that doesn't have any arguments and doesn't return anything
type Func
type Func = (...args: any[]) => any;
Generic "Function" type, because typescript does not like using "Function" directly in strict mode
type HookOptionsEither
type HookOptionsEither = mongoose.SchemaPreOptions | mongoose.SchemaPostOptions;
A Helper type to combine both mongoose Hook Option types
type ModelType
type ModelType<T, QueryHelpers = BeAnObject> = mongoose.Model< DocumentType<T, QueryHelpers>, QueryHelpers>;
Used Internally for ModelTypes
type NestedDiscriminatorsMap
type NestedDiscriminatorsMap = Map<string, DiscriminatorObject[]>;
Type for the Values stored in the Reflection for Nested Discriminators
Example 1
const disMap: NestedDiscriminatorsMap = new Map(Reflect.getMetadata(DecoratorKeys.NestedDiscriminators, target) ?? []);
type PropOptionsForNumber
type PropOptionsForNumber = BasePropOptions & ValidateNumberOptions;
type PropOptionsForString
type PropOptionsForString = BasePropOptions & TransformStringOptions & ValidateStringOptions;
type QueryHelperThis
type QueryHelperThis< T extends AnyParamConstructor<any>, QueryHelpers, S = DocumentType<T, QueryHelpers>> = mongoose.QueryWithHelpers<S | null, S, QueryHelpers>;
Helper type to easily set the
this
type in a QueryHelper functionExample 1
function findById(this: QueryHelperThis<YourClass, YourClassQueryHelpers>, id: string) { return this.findOne({ _id: id }); }
type QueryMethodMap
type QueryMethodMap = Map<string, Func>;
Type for the Values stored in the Reflection for Query Methods
Example 1
const queryMethods: QueryMethodMap = new Map(Reflect.getMetadata(DecoratorKeys.QueryMethod, target) ?? []);
type Ref
type Ref< PopulatedType, RawId extends mongoose.RefType = | (PopulatedType extends { _id?: mongoose.RefType; } ? NonNullable<PopulatedType['_id']> : mongoose.Types.ObjectId) | undefined> = mongoose.PopulatedDoc<PopulatedType, RawId>;
Reference another Model
type RefType
type RefType = mongoose.RefType;
type ReturnModelType
type ReturnModelType< U extends AnyParamConstructor<any>, QueryHelpers = BeAnObject> = ModelType<InstanceType<U>, QueryHelpers> & U;
The Type of a Model that gets returned by "getModelForClass" and "setModelForClass"
type VirtualPopulateMap
type VirtualPopulateMap = Map<string, any & VirtualOptions>;
Type for the Values stored in the Reflection for Virtual Populates
Example 1
const virtuals: VirtualPopulateMap = new Map(Reflect.getMetadata(DecoratorKeys.VirtualPopulate, target.constructor) ?? []);
Package Files (15)
Dependencies (5)
Dev Dependencies (32)
- @commitlint/cli
- @commitlint/config-conventional
- @deepkit/core
- @deepkit/type
- @semantic-release/changelog
- @semantic-release/commit-analyzer
- @semantic-release/git
- @semantic-release/github
- @semantic-release/npm
- @semantic-release/release-notes-generator
- @types/jest
- @types/lodash
- @types/node
- @types/semver
- @typescript-eslint/eslint-plugin
- @typescript-eslint/parser
- class-transformer
- commitlint
- eslint
- eslint-config-prettier
- eslint-plugin-prettier
- husky
- jest
- lint-staged
- mongodb-memory-server
- mongoose
- mongoose-findorcreate
- prettier
- rimraf
- semantic-release
- ts-jest
- typescript
Peer Dependencies (1)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@typegoose/typegoose
.
- Markdown[](https://www.jsdocs.io/package/@typegoose/typegoose)
- HTML<a href="https://www.jsdocs.io/package/@typegoose/typegoose"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 5733 ms. - Missing or incorrect documentation? Open an issue for this package.