Based on mongoose's documentation, I tried to create a chainable byYear
query helper method as follows:
import * as mongoose from 'mongoose'
import { IMovie } from '../interfaces/movies'
export interface MovieDocument extends IMovie, mongoose.Document {}
const schema = new mongoose.Schema({
id: {
type: String,
required: [true, 'Missing ID'],
index: { unique: true },
},
title: { type: String, required: [true, 'Missing title'] },
year: Number,
director: String,
actor: [String],
})
schema.query.byYear = function (year) {
return this.find({ year: year })
}
export const Movie = mongoose.model<MovieDocument>(
'Movies',
schema,
'Movies'
)
where IMovie
is a simple interface
having the same fields as the schema
.
Then I tried using my query helper:
Movie.find().byYear(year).then(movies => {
console.log('found these movies:', movies)
}).catch(err => {
console.log('error:' + err)
})
But I get Property 'byYear' does not exist on type 'Query<MovieDocument[], MovieDocument, {}>'
for the Movie.find().byYear()
part. Nevertheless, the code seems to work, but it seems that due to insufficient typing VS Code does not realize that the Query
returned by Movie.find()
actually does have a byYear
method. How do I do this properly?
UPDATE 2021-05-02: I should have emphasized more that the code I present works beautifully. My problem and the matter of the question is more geared towards how to correctly 'type' this in TypeScript or simply why the error occurs.