Mongoose and Typescript Model requirement function

血红的双手。 提交于 2021-02-11 14:02:30

问题


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);

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?

Thanks.


回答1:


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);


来源:https://stackoverflow.com/questions/59615773/mongoose-and-typescript-model-requirement-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!