问题
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