Node.js – Typescript and Mongoose Model

modelmongoosenode.jstypescript

I 'm trying to bind my Model with a mongoose schema using Typescript.
I have my IUser interface:

export interface IUser{

   _id: string;

   _email: string;
}

My User class:

export class User implements IUser{
  _id: string;
  _email: string;
}

My RepositoryBase:

export class RepositoryBase<T extends mongoose.Document> {

 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);
 }
}

And finally my UserRepository which extends RepositoryBase and implements an IUserRepository (actually empty):

export class UserRepository  extends RepositoryBase<IUser> implements     IUserRepository{

  constructor(){
    super(mongoose.model<IUser>("User", 
        new mongoose.Schema({
            _id: String,
            _email: String,
        }))
    )
  }

}

Thr problem is that typescript compiler keeps saying :
Type 'IUser' does not satisfy the constraint 'Document'

And if I do:

export interface IUser extends mongoose.Document

That problem is solved but the compiler says:
Property 'increment' is missing in type 'User'

Really, i don't want my IUser to extend mongoose.Document, because neither IUser or User should know about how Repository work nor it's implementation.

Best Answer

I solved the issue by referencing this blog post.

The trick was to extends the Document interface from mongoose like so:

import { Model, Document } from 'mongoose';

interface User {
  id: string;
  email: string;
}

interface UserModel extends User, Document {}

Model<UserModel> // doesn't throw an error anymore