I am encountering two issues while defining a schema using mongoose and typescript. Below is the code snippet I'm having trouble with:
import { Document, Schema, Model, model} from "mongoose";
export interface IApplication {
id: number;
name: string;
virtualProperty: string;
}
interface IApplicationModel extends Document, IApplication {} //Issue 1
let ApplicationSchema: Schema = new Schema({
id: { type: Number, required: true, index: true, unique: true},
name: { type: String, required: true, trim: true },
});
ApplicationSchema.virtual('virtualProperty').get(function () {
return `${this.id}-${this.name}/`; // Issue 2
});
export const IApplication: Model<IApplicationModel> = model<IApplicationModel>("Application", ApplicationSchema);
Firstly:
- Issue 1 arises in this line:
interface IApplicationModel extends Document, IApplication {}
The Typescript compiler is reporting:
error TS2320: Interface 'IApplicationModel' cannot simultaneously extend types 'Document' and 'IApplication'.
Named property 'id' of types 'Document' and 'IApplication' are not identical.
How can I modify the definition of the id
property to resolve this?
Issue 2 lies within the inner function (getter for
virtualProperty
):return `${this.id}-${this.name}/; // Issue 2
The Error message indicates:
error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.
What is the correct way to define the type of this
in this context?