Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript and Mongoose Model

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.

like image 353
JVilla Avatar asked Sep 12 '16 17:09

JVilla


People also ask

Can mongoose be used with TypeScript?

Mongoose introduced officially supported TypeScript bindings in v5. 11.0. Mongoose's index.

What does mongoose model do?

Model. A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.

What is schema in TypeScript?

A Schema represents an ECSchema in TypeScript. It is a collection of Entity-based classes. See the BIS overview for how ECSchemas are used to model information. ECSchemas define classes for models, elements, and aspects, as well as ECRelationships.

Is mongoose ODM or ORM?

Mongoose is an ODM that provides a straightforward and schema-based solution to model your application data on top of MongoDB's native drivers.


1 Answers

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

like image 51
Mateja Petrovic Avatar answered Sep 18 '22 18:09

Mateja Petrovic