简体   繁体   中英

How to avoid writing the Schema of Mongoose twice when using it with TypeScript?

I am trying to use Mongoose together with TypeScript.

With JavaScript alone, we can pretty easily write the schema for a model Foo .

const fooSchema = new mongoose.Schema({
  name: String,
  value: Number
});

fooSchema.methods.someInstanceMethod = function() {/*...*/};

fooSchema.statics.someStaticMethod = function() {/*...*/};

const Foo = mongoose.model('Foo', fooSchema);

And we can use Foo like so:

Foo.someStaticMethod();
var foo = new Foo();
foo.someInstanceMethod();
foo.name;

-

However, now that we have TypeScript, we will get error messages:

Property 'someStaticMethod' does not exist on type 'Model'.

Property 'someInstanceMethod' does not exist on type 'Document'.

Property 'name' does not exist on type 'Document'.

After some research, I gathered that the way to fix this is to declare the following interfaces:

export interface IFooDocument extends mongoose.Document {
  name: string;
  value: number;
  someInstanceMethod(): any;
}

export interface IFooModel extends mongoose.Model<IFooDocument> {
  someStaticMethod(): any;
}

And adjust Foo to be:

export const Foo = <IFooModel>mongoose.model<IFooDocument>('Foo', fooSchema);

-

The issue I have with this approach is that we essentially need to rewrite the Schema twice - once on fooSchema , and once on the interfaces. To me, the necessity of having to make sure the interface and schema are always kept in sync introduces just as many problems as type checking solves.

So my question is: Is there a way to avoid having to rewrite the Schema twice and still use types? Is there a better way to keep the schema and interface in sync?

Or alternatively, perhaps Mongoose is not the right ODM solution if I am using TypeScript? Is there a better solution?

Or alternatively, perhaps Mongoose is not the right ODM solution if I am using TypeScript? Is there a better solution?

I would be happy to offer you this library: https://github.com/doublemcz/mongo-odm

It is based on Native Client with focus on ease-of-use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM