Edgaras Karka
Edgaras Karka

Reputation: 7852

mongoose schema.method not working : TypeScript error TS2339: Property 'myMethod' does not exist on type 'Model<MyModelI>'

I want to use mongoose with TypeScript. Also, I want to extend Model functionality to add the new method.

But when call tsc to transpile file I get:

spec/db/models/match/matchModelSpec.ts(47,36): error TS2339: Property 
'findLeagueMatches' does not exist on type 'Model<MatchModelI>'.

MatchModel.ts:

import {MatchInterface} from "./matchInterface";
import {Schema, model, Model, Document} from "mongoose";

export interface MatchModelI extends MatchInterface, Document {
    findLeagueMatches(locationName: String, leagueName: String): Promise<MatchModelI[]>;
}
export let matchSchema: Schema = new Schema({
    startTime: {type: Date, required: true},
    location: {type: Schema.Types.ObjectId, ref: 'Location'},
    league: {type: Schema.Types.ObjectId, ref: 'League'}
});

matchSchema.methods.findLeagueMatches = function(locationName: String, leagueName: String){
    //...
    return matches;
};

export const Match: Model<MatchModelI> = model<MatchModelI>("Match", matchSchema);

Upvotes: 1

Views: 1523

Answers (1)

Edgaras Karka
Edgaras Karka

Reputation: 7852

It works:

import {Schema, Model, model, Document} from "mongoose";
import {LeagueInterface} from "./leagueInterface";
import {MatchModelI, Match} from "../match/matchModel";
import {LocationModelI} from "../location/locationModel";

export interface ILeagueDocument extends Document {
    name: string;
    location: LocationModelI;
}

export interface LeagueModelI extends Model<ILeagueDocument>{
    getAllMatches(): Promise<MatchModelI[]>
}

export let leagueSchema: Schema = new Schema({
    name: { type: String, required: true },
    location: {type: Schema.Types.ObjectId , ref: 'Location', required: true},
});

const getAllMatches = async function ():Promise<MatchModelI[]>{
    return Match.find({league: this._id}).exec();
};

leagueSchema.method('getAllMatches', getAllMatches);


/** @class Match */
export const League: LeagueModelI = model<ILeagueDocument, LeagueModelI>("League", leagueSchema);

Upvotes: 1

Related Questions