Annotations for mongoose
Provides basic annotations to get started with mongoose in typescript
npm i mongoose-annotations
API:
field = <T>(options?: SchemaTypeOpts<T>): PropertyDecorator
- options: Field options. eg: index, default etc
- when options is not provided the type information is gathered with
reflect-metadata
, all simple types can easily be gathered@field() name?: string
=>{ type: String }
@field() count?: number = 100
=>{ type: String, default: 100 }
The default is figured by callingnew MySchema
, so it's necessary that constructor overrides must have default values. This behaviour can be disabled usingsetDefaults({...})
@field() date?: Date
=>{ type: Date }
@field({type: String}) value?: number
=>{ type: String }
options have higher preference.
schema = (options?: SchemaOptions): ClassDecorator
- options: mongoose schema options. eg: disable _id, add timestamps
collection = (name: string, target: any, skipInit = false): ClassDecorator
- name : collection name for database
- target: class that decorated with schema or field
- skipInit: skip schema initialisation
arrayOf = (target: any): [SchemaType]
optional, added for the purpose of improving readability- target: Any mongoose allowed types
function MongooseModel<T, F = {}>(): Model<T & Document, F>
This function is totally unnecessary, but this adds type information to the extended model, thus increases readability and correctness.type Doc<T> = T & MongooseDocument;
This type adds annotation for field/method made available in subschema by mongoose implicitlyenumValues<T>(value: any): any[]
returns values for typescript enum.class MongooseSchema
optionally extended by schema class to access compiled schema
check example for usage:
;
Model usage
connect first, always connect first.
connect"mongodb://localhost:27017/myapp", ;
Indices
User.schema.index; User.createIndexes;
Fetch and save
User.findById"5f42181555791f7879cfaebc" .exec .then
License
MIT - No warranty