从打字稿类生成猫鼬模式/模型的最佳方法是什么?

时间:2019-09-27 00:43:16

标签: mongodb typescript mongoose

在网上快速搜索后,我找到了这些引用,但是它们仍然需要额外的架构定义:

  1. https://mongoosejs.com/docs/4.x/docs/advanced_schemas.html
  2. https://codingsans.com/blog/mongoose-models-using-typescript-classes
  3. https://gist.github.com/brennanMKE/ee8ea002d305d4539ef6

没有办法吗?

对于大型项目,为每个类/模型复制代码似乎是个坏主意。

我正在寻找这样的东西:

// Animal.ts
class _Animal {
  private _name: string;
  private _weight: number;

  constructor(name: string = "", weight: number = 0.0) {
    this._name = name;
    this._weight = weight;
  }

  get name(): string {
    return this._name;
  }

  get weight(): number {
    return this._weight;
  }

  eat() {
    // ...
  }
}

const Animal = mongoose.model(_Animal);
module.exports = Animal;

// Main.ts
import {Animal} from "Animal";
let myCat = new Animal("Logan", 5.8);
// ...

0 个答案:

没有答案