Replies: 1 comment
-
This is because you're turning off Mongoose's automatic type inference by passing the document interface as a generic to import { Schema } from 'mongoose';
/*interface Item {
name?: string;
}*/
const itemSchema = new Schema({
name: String,
});
/*interface Shop {
items: Item[];
}*/
const shopSchema = new Schema(
{
items: {
type: [itemSchema],
required: true,
},
},
{
virtuals: {
isFull: {
// get(): boolean {
// // this is `any` type
// return this.items.length > 15;
// },
get(): boolean {
const length: number = this.items.length;
return length > 15;
},
},
},
},
); If you want to continue passing in document interface, you would also need to pass in the virtual interface: import { Model, Schema } from 'mongoose';
interface Item {
name?: string;
}
const itemSchema = new Schema({
name: String,
});
interface Shop {
items: Item[];
}
interface ShopVirtuals {
isFull: boolean;
}
const shopSchema = new Schema<Shop, Model<Shop>, {}, {}, ShopVirtuals>(
{
items: {
type: [itemSchema],
required: true,
},
},
{
virtuals: {
isFull: {
get(): boolean {
const length: number = this.items.length;
return length > 15;
},
},
},
},
); |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Didn't find any information from typescript documentation.
The
this
is inferred to beany
instead ofshop
document. Currently, I have to specify the type forthis
explicitly. Is this the currently recommended way?mongoose: 7.4.0
typescript: ^5.1.6
Beta Was this translation helpful? Give feedback.
All reactions