Recently, I've been delving into typescript and mongodb for a few days now. I decided to implement a custom method that can be executed on Document
instances. Let me share my setup:
import { Document, Schema, model, Model } from "mongoose";
import { AlbumSchema, AlbumDocument } from './album';
Below is my Document interface definition:
interface ArtistDocument extends Document {
name: string;
identifier: string;
albums: [AlbumDocument];
testFunction(): string
}
Here's how I defined the Schema:
const ArtistSchema = new Schema({
name: {type: String, required: true},
identifier: {type: String, required: true},
albums: {type: [AlbumSchema], required: true, default: []}
});
ArtistSchema.methods.testFunction = function(): string {
return "Hello World";
}
While I am able to call testFunction();
on an instance of Artist
, everything seems to work fine. However, here comes the issue:
ArtistSchema.methods.testFunction = function(): string {
return "Albums:" + this.albums.length;
}
The problem lies in this.albums
being treated as type any
instead of AlbumDocument[]
. This limitation hinders me from using array functions or accessing properties of AlbumDocument
.
Could you point out where I might have gone wrong? Any suggestions for resolving this?