[英]Typescript and Mongoose Model
I 'm trying to bind my Model with a mongoose schema using Typescript. 我正在尝试使用Typescript将我的模型与mongoose模式绑定。 I have my IUser interface: 我有我的IUser界面:
export interface IUser{
_id: string;
_email: string;
}
My User class: 我的用户类:
export class User implements IUser{
_id: string;
_email: string;
}
My RepositoryBase: 我的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);
}
}
And finally my UserRepository which extends RepositoryBase and implements an IUserRepository (actually empty): 最后我的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 problem is that typescript compiler keeps saying : Type 'IUser' does not satisfy the constraint 'Document' 问题是打字稿编译器一直说: 类型'IUser'不满足约束'Document'
And if I do: 如果我这样做:
export interface IUser extends mongoose.Document
That problem is solved but the compiler says: Property 'increment' is missing in type 'User' 该问题已得到解决,但编译器说: “用户”类型中缺少“属性'增量'
Really, i don't want my IUser to extend mongoose.Document, because neither IUser or User should know about how Repository work nor it's implementation. 真的,我不希望我的IUser扩展mongoose.Document,因为IUser或User都不应该知道Repository如何工作以及它的实现。
I solved the issue by referencing this blog post . 我通过参考这篇博客文章解决了这个问题。
The trick was to extends the Document
interface from mongoose
like so: 诀窍是从像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.