My function save of an object (in model.ts file) which is created by typegoose should return Promise<Todo>
but it returns Promise<Document<any, {}>>
and i have this error :
Type 'Document<any, {}>' is missing the following properties from type 'Todo': createdAt, updatedAt, content, isDone
How should i correct this ?
model ts
import { getModelForClass } from "@typegoose/typegoose";
import { ObjectId } from "mongodb";
import { Todo } from "../../entities";
import { NewTodoInput } from "./input";
// This generates the mongoose model for us
export const TodoMongooseModel = getModelForClass(Todo);
export default class TodoModel {
async getById(_id: ObjectId): Promise<Todo | null> {
// Use mongoose as usual
return TodoMongooseModel.findById(_id).lean().exec();
}
async create(data: NewTodoInput): Promise<Todo> {
const todo = new TodoMongooseModel(data);
return todo.save();
}
}
input ts
import { Field, InputType, ID } from "type-graphql";
import { MaxLength, MinLength } from "class-validator";
@InputType()
export class NewTodoInput {
@Field()
@MaxLength(300)
@MinLength(1)
content: string | undefined;
}
entities todo ts
import { ObjectType, Field } from "type-graphql";
import { prop } from "@typegoose/typegoose";
import { ObjectId } from "mongodb";
@ObjectType()
export class Todo {
@Field()
readonly _id!: ObjectId;
@prop()
@Field(() => Date)
createdAt!: Date;
@prop()
@Field(() => Date)
updatedAt!: Date;
@prop()
@Field()
content!: string;
@prop({ default: false })
@Field()
isDone!: boolean;
}
Thank you.
with the unofficial mongoose types, it is an known problem that await document.save()
does not return the correct typings
-> this is not an problem with typegoose, it is with @types/mongoose
the workaround is to use:
await doc.save();
return doc;
(or maybe in your case directly use the mongoose provided function .create
)
PS: this is not a problem in the official types of mongoose (can be currently used with typegoose 8.0.0-beta.x
)