【问题标题】:Unable to use mongoose virtual with typescript无法将猫鼬虚拟与打字稿一起使用
【发布时间】:2021-09-27 22:58:51
【问题描述】:

我正在尝试学习如何将虚拟机与猫鼬和打字稿一起使用。

假设我有一个用户界面。

interface User {
    id: mongoose.ObjectId;
    name: string;
    likes: string;
}

然后我为猫鼬创建一个模式。

// create the model
const user: mongoose.SchemaDefinition<User> = {
    name: { type: String },
    likes: { type: String },
};

// enable the use of virtuals
const options: mongoose.SchemaOptions = {
    toJSON: { getters: true, virtuals: true },
    toObject: { virtuals: true },
};

// create the scheme
const schema = new Schema(user, options);

然后我去添加一个虚拟并创建我的模型。

// attach the virtual "bio" to return a string about the user
schema.virtual("bio").get(function (): string {
    return `Hi my name is ${this.name} and i like ${this.likes}`;
});

const model = mongoose.model("User", schema);

但是,像上面那样创建虚拟会在this 上产生此错误。见下图。

所以我想我可以根据this post修改我的虚拟。

schema.virtual("bio").get(function (this: User): string {
    return `Hi my name is ${this.name} and i like ${this.likes}`;
});

const model = mongoose.model("User", schema);

但这对我不起作用,因为我的理论是在我的 tsconfig "noUnusedLocals": true 中设置了以下内容。我不想禁用它,因为它是一个有用的 linting 规则。见下图。

所以我的问题是如何在 typescript 中创建一个不会引发此类错误的 mongoose virtual,是否有一个简单的示例我在谷歌搜索时错过了?

我想一种解决方案是在上面的行中添加// eslint-disable-next-line no-unused-vars 以抑制警告。然而,这并不能解释为什么 this 是“未使用的”。虽然是这样。

我什至尝试通过将this 设置为临时变量(它为用户界面获取 IntelliSense,因此它不像忽略输入)来专门使用 this

schema.virtual("bio").get(function (this: IUserModel): string {
    const name = this.name;
    const like = this.likes;
    return `Hi my name is ${name} and i like ${like}`;
});

这是我作为一个复制粘贴友好 Blob 的完整示例。

interface User {
    id: mongoose.ObjectId;
    name: string;
    likes: string;
}

const user: mongoose.SchemaDefinition<User> = {
    name: { type: String },
    likes: { type: String },
};

const options: mongoose.SchemaOptions = {
    toJSON: { getters: true, virtuals: true },
    toObject: { virtuals: true },
};

const schema = new Schema(user, options);

// this is defined but never used :(
schema.virtual("bio").get(function (this: User): string {
    return `Hi my name is ${this.name} and i like ${this.likes}`;
});

const model = mongoose.model("User", schema);

export default model;

【问题讨论】:

  • 不知道为什么这对你不起作用,它对我很有效(见tsplay.dev/wOzxzW
  • 也许,问题在于您使用的是new Schema() 而不是new mongoose.Schema()(不过,它前面的所有其他内容都以mongoose. 开头),并且它意外地解析为其他一些现有的类,与猫鼬?

标签: node.js typescript mongodb mongoose


【解决方案1】:

如果您正在使用 typescript,则需要设置这些属性

user.set("toObject", { virtuals: true });
user.set("toJSON", { virtuals: true });

【讨论】:

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