【问题标题】:Typescript and Mongoose Model打字稿和猫鼬模型
【发布时间】:2017-01-20 04:46:56
【问题描述】:

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

export interface IUser{

   _id: string;

   _email: string;
}

我的用户类:

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

我的存储库:

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,
        }))
    )
  }

}

Thr 问题是打字稿编译器一直在说: 类型'IUser'不满足约束'Document'

如果我这样做:

export interface IUser extends mongoose.Document

这个问题已经解决了,但是编译器说: “用户”类型中缺少属性“增量”

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

【问题讨论】:

  • 谢谢哈利,这非常有用。但是“export mongoose.model("User", userSchema)”我应该在我的 User 类中执行此操作。但后来我放弃了我所有的方法,不是吗?
  • 遇到同样的问题。有人可以帮忙吗?

标签: node.js typescript mongoose model


【解决方案1】:

我通过引用this blog post解决了这个问题。

诀窍是从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

【讨论】:

    猜你喜欢
    • 2014-02-15
    • 2018-10-09
    • 1970-01-01
    • 2016-02-05
    • 2020-05-11
    • 1970-01-01
    • 2017-06-30
    • 2018-10-24
    • 2016-04-01
    相关资源
    最近更新 更多