Mongoose the Typescript way…?

后端 未结 14 560
遥遥无期
遥遥无期 2020-11-28 19:27

Trying to implement a Mongoose model in Typescript. Scouring the Google has revealed only a hybrid approach (combining JS and TS). How would one go about implementing the

14条回答
  •  死守一世寂寞
    2020-11-28 20:03

    Most answers here repeat the fields in the TypeScript class/interface, and in the mongoose schema. Not having a single source of truth represents a maintenance risk, as the project becomes more complex and more developers work on it: fields are more likely to get out of sync. This is particularly bad when the class is in a different file vs. the mongoose schema.

    To keep fields in sync, it makes sense to define them once. There are a few libraries that do this:

    • typeodm.io - full test coverage, good examples, no traction yet
    • mongoose-decorators-ts - best English, no traction yet
    • typegoose - most popular, documentation needs improvement
    • ts-mongoose - doesn't use decorators, second most popular, not actively maintained
    • mongoose-schema-decorators - no traction yet
    • mongoose-typescript - fork of typegoose

    I haven't yet been fully convinced by any of them but typegoose seems actively maintained, and the developer accepted my PRs.

    To think one step ahead: when you add a GraphQL schema into the mix, another layer of model duplication appears. One way to overcome this problem might be to generate TypeScript and mongoose code from the GraphQL schema.

提交回复
热议问题