【问题标题】:Use es6 classes with mongoose in typescript with loadClass在带有 loadClass 的打字稿中使用 es6 类和猫鼬
【发布时间】:2021-04-26 09:17:25
【问题描述】:

我有这个问题,我已经搜索了整个谷歌没有任何答案。我试图通过加载类(即 schema.loadClass(class))来使用 es6 类和猫鼬,但是打字稿抛出错误,说类中缺少成员。像这样的:

//user.model.ts

import {Schema, model, Document} from "mongoose"
import User from "./user"

const schema = new Schema({
name:String,
age:Number, 
})

export interface IUser{
name:string;
age:number;
}

schema.loadClass(UserClass)
export const User = model<IUser>("User", schema)
//user.ts


export default class UserClass{
  intro():string{
return `my name is ${this.name} and I am ${this.age} years old`
}
}

虽然,这是一个例子,有没有办法解决这个问题?您刚刚通过回答这个问题拯救了一个家庭,谢谢。

【问题讨论】:

  • 这很有趣。我可以立即看到一些问题,但我需要研究解决方案。您的class UserClassIUser 接口一无所知,因此在访问this.namethis.age 时会报错,因为这些属性未在UserClass 上定义。由于这个原因,class 可能在这里没有意义。
  • 查看示例mongoosejs.com/docs/advanced_schemas.html 很难看出它如何与 typescript 一起工作,因为我们需要让 typescript 知道仅在运行时可用的属性,而 typescript 在编译时运行这些属性不存在。
  • 基于此答案:stackoverflow.com/a/54724614/10431574 我认为这可行:tsplay.dev/nWPakw 如果有任何具体错误,请告诉我。
  • 它抱怨“this”的上下文使用方式不同,因为我有一个妈妈类调用Userclass.info()。我不得不使用 //@ts-ignore 来消除错误

标签: node.js mongodb typescript mongoose es6-class


【解决方案1】:

看起来我们已经有了答案here

你的实现类 UserClass 应该是这样的

export default class UserClass {
  intro(this: IUser): string {
    return `my name is ${this.name} and I am ${this.age} years old`;
  }
}

UserClass 假定 this 是它自己的对象,除非你另有定义。

另外,你也可以像这样修改user.model.ts

import { Schema, connection, Document } from "mongoose"
import User from "./user"

export interface IUser {
  name: string,
  age: number,
  intro(): string, // to get it via intellisense, user.intro()
}
type IntroDocument = IUser & Document;

const schema = new Schema<IntroDocument>({
  name: String,
  age: Number,
})

schema.loadClass(UserClass);
export const User = connection.model<IUser>("User", schema);

编辑:与 OP 发布的方式不同,请注意,model 需要从 connection 对象(mongoose v5.11.13)导入。

【讨论】:

    猜你喜欢
    • 2021-01-05
    • 2020-05-11
    • 2020-06-21
    • 1970-01-01
    • 2017-01-20
    • 2016-02-05
    • 2016-06-14
    • 2017-06-30
    • 2017-04-11
    相关资源
    最近更新 更多