2

I'm attempting to use Mongoose 4.5.4 and it's typings in NodeJS with Typescript (obviously) while utilizing the Repository Pattern.

RepositoryBase:

export class RepositoryBase<T extends mongoose.Document> implements IRead<T>, IWrite<T> {
    private _model: mongoose.Model<mongoose.Document>;

    constructor(schemaModel: mongoose.Model<mongoose.Document>) {
        this._model = schemaModel;
    }

    create(item: T): mongoose.Promise<mongoose.model<T>> {
        return this._model.create(item);
    }

    //......
    //Additional CRUD methods excluded for brevity
}

UserRepository:

export class UserRepository extends RepositoryBase<IUserModel> {
    constructor() {
        super(UserSchema);
    }
}

I have the following type error on the call to super() from UserRepository

[ts] Argument of type '<U>(name: string) => IModelConstructor<U> & EventEmitter' is not assignable to parameter of type 'IModelConstructor<Document> & EventEmitter'. Type '<U>(name: string) => IModelConstructor<U> & EventEmitter' is not assignable to type 'IModelConstructor<Document>'. Property 'findById' is missing in type '<U>(name: string) => IModelConstructor<U> & EventEmitter'. import UserSchema

Does anyone know why? My creation of my model (UserSchema) is very simple: let model = mongooseConnection.model<IUserModel>("Users", UserSchema.schema);

I would much appreciate a push in the right direction.

Fedoranimus
  • 816
  • 6
  • 20
  • See 2 solutions here: https://stackoverflow.com/questions/34482136/mongoose-the-typescript-way (Disclaimer: one of them is mine) – Gábor Imre Aug 11 '16 at 12:24

1 Answers1

2

Doing a simple export const model = mongooseConnection.model<IUserModel>("Users", UserSchema.schema); was enough to solve this typing issue.

Fedoranimus
  • 816
  • 6
  • 20