简体   繁体   English

使用TypeScript时如何避免两次编写Mongoose Schema?

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

I am trying to use Mongoose together with TypeScript. 我正在尝试将Mongoose与TypeScript一起使用。

With JavaScript alone, we can pretty easily write the schema for a model Foo . 仅使用JavaScript,我们就可以非常轻松地为模型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

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

- -

However, now that we have TypeScript, we will get error messages: 但是,现在我们有了TypeScript,我们将收到错误消息:

Property 'someStaticMethod' does not exist on type 'Model'. “模型”类型中不存在属性“someStaticMethod”。

Property 'someInstanceMethod' does not exist on type 'Document'. “文档”类型中不存在属性“someInstanceMethod”。

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: 并调整Foo为:

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. 我对这种方法的问题是我们基本上需要重写Schema两次 - 一次在fooSchema ,一次在接口上。 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? 所以我的问题是:有没有办法避免重写Schema两次仍然使用类型? 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? 或者,如果我使用TypeScript,也许Mongoose不是正确的ODM解决方案? 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 我很乐意为您提供这个库: https//github.com/doublemcz/mongo-odm

It is based on Native Client with focus on ease-of-use. 它基于Native Client,侧重于易用性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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