繁体   English   中英

打字稿和猫鼬模型

[英]Typescript and Mongoose Model

我正在尝试使用Typescript将我的模型与mongoose模式绑定。 我有我的IUser界面:

export interface IUser{

   _id: string;

   _email: string;
}

我的用户类:

export class User implements IUser{
  _id: string;
  _email: string;
}

我的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);
 }
}

最后我的UserRepository扩展了RepositoryBase并实现了一个IUserRepository(实际上是空的):

export class UserRepository  extends RepositoryBase<IUser> implements     IUserRepository{

  constructor(){
    super(mongoose.model<IUser>("User", 
        new mongoose.Schema({
            _id: String,
            _email: String,
        }))
    )
  }

}

问题是打字稿编译器一直说:

如果我这样做:

export interface IUser extends mongoose.Document

该问题已得到解决,但编译器说:

真的,我不希望我的IUser扩展mongoose.Document,因为IUser或User都不应该知道Repository如何工作以及它的实现。

我通过参考这篇博客文章解决了这个问题。

诀窍是从像mongoose扩展Document接口,如下所示:

import { Model, Document } from 'mongoose';

interface User {
  id: string;
  email: string;
}

interface UserModel extends User, Document {}

Model<UserModel> // doesn't throw an error anymore

暂无
暂无

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

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