Last active
June 27, 2019 08:40
-
-
Save angryziber/b5bf9d1b21813f38f45e238fc6bba6de to your computer and use it in GitHub Desktop.
Typegoose without extending
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// If you want to use Mongoose with TypeScript, you are in trouble. | |
// Typegoose comes to the rescue, but it requires model classes to extend Typegoose class, | |
// which breaks using model classes as interfaces for casting in your code | |
// Here is the solution: don't extend Typegoose and use this function to create your models: | |
import {InstanceType, Typegoose} from 'typegoose' | |
import {Connection, Model} from 'mongoose' | |
function buildModel<T, U>(constructor: {new (): T} & U, db: Connection, collectionName: string): Model<InstanceType<T>> & U { | |
const instance = new constructor() as any; | |
instance.buildSchema = (Typegoose.prototype as any).buildSchema; | |
return Typegoose.prototype.setModelForClass.call(instance, constructor, { | |
existingConnection: db, schemaOptions: {collection: collectionName} | |
}) as any; | |
} | |
// This is hacky, and I wish Typegoose could include something like this by default instead of a base class |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment