Mongoose 和 Typescript 模型需求函数 [英] Mongoose and Typescript Model requirement function

查看:56
本文介绍了Mongoose 和 Typescript 模型需求函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 mongoose 的 typescript 中创建一个模型,我想使用一个必需的函数,但是与普通的 javascript 不同,我不能使用this"运算符,因为 typescript 无法识别范围.我想访问另一个对象属性的值,但我不知道该怎么做.这是我要找的:

I am creating a model in typescript in mongoose and I would like to use a required function, however unlike normal javascript, I cannot use the 'this' operator as typescript doesn't recognize the scope. I would like to access the value of another one of the objects properties, but I am not sure how to do it. Here is what I am looking for:

export interface IUser extends mongoose.Document {
  name: string; 
  somethingElse?: number; 
};

export const UserSchema = new mongoose.Schema({
  name: {type:String, required: true},
  somethingElse: required: function() {
     // use this.name here ......
  }

});

const User = mongoose.model<IUser>('User', UserSchema);

在这个例子中,我希望能够访问'this.name',但是打字稿不理解这个方法.在打字稿中执行此操作的正确方法是什么?

In this example, I would like to be able to access 'this.name', but typescript doesn't understand this method. What is the proper way to do this in typescript?

谢谢.

推荐答案

不确定这是否是最好的方法,但您尝试过吗?

Not sure if it's the best way to do it, but have you tried this ?

export interface IUser extends mongoose.Document {
  name: string; 
  somethingElse?: number; 
};

export const UserSchema = new mongoose.Schema({
  name: {type:String, required: true},
});

UserSchema.obj.somethingElse.required = function () {
  // use this.name here ......
}

const User = mongoose.model<IUser>('User', UserSchema);

这篇关于Mongoose 和 Typescript 模型需求函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆