Skip to content

Instantly share code, notes, and snippets.

@angryziber
Last active June 27, 2019 08:40
Show Gist options
  • Save angryziber/b5bf9d1b21813f38f45e238fc6bba6de to your computer and use it in GitHub Desktop.
Save angryziber/b5bf9d1b21813f38f45e238fc6bba6de to your computer and use it in GitHub Desktop.
Typegoose without extending
// 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