I recently started using typegoose and nestjs for my backend-server. In my pages.service.ts
file, I already have a function called getPageById()
to retrieve a single page by its ID. However, when trying to call this function from another function within the same file, TypeScript throws the following error:
Property 'save' does not exist on type 'page'
The structure of my page.model.ts
file is as follows:
import { DocumentType, modelOptions, prop, Severity } from "@typegoose/typegoose";
import { Content } from "./models/content.model";
@modelOptions({
schemaOptions: {
timestamps: true,
toJSON: {
transform: (doc: DocumentType<Page>, ret) => {
delete ret.__v;
ret.id = ret._id;
delete ret._id;
}
}
},
options: {
allowMixed: Severity.ALLOW
}
})
export class Page {
@prop({required: true})
title: string;
@prop({required: true})
description: string;
@prop({required: true})
content: Content;
@prop()
createdAt?: Date;
@prop()
updatedAt?: Date;
@prop()
category: string;
}
Meanwhile, the contents of my pages.service.ts
file are as follows:
import { Injectable, NotFoundException } from '@nestjs/common';
import { ReturnModelType } from '@typegoose/typegoose';
import { InjectModel } from 'nestjs-typegoose';
import { createPageDto } from './dto/create-page.dto';
import { Page } from './page.entity';
@Injectable()
export class PagesService {
constructor(
@InjectModel(Page)
private readonly pageModel: ReturnModelType<typeof Page>
) {}
async getPageById(id: string): Promise<Page> {
let page;
try {
page = await this.pageModel.findById(id);
} catch (error) {
throw new NotFoundException(`Page could not be found`);
}
if (!page) {
throw new NotFoundException(`Page could not bet found`);
}
return page;
}
async updatePageCategory(id: string, category: string): Promise<Page> {
const page = await this.getPageById(id);
page.category = category;
page.save() // the error occurs here
return page;
}
}
Any suggestions on how to resolve this issue would be greatly appreciated.
Update:
After some investigation, I managed to fix the bug by changing the return type to
Promise<DocumentType<Page>>
like so:
async getPageById(id: string): Promise<DocumentType<Page>> {
let page;
try {
page = await this.pageModel.findById(id);
} catch (error) {
throw new NotFoundException(`Page could not be found`);
}
if (!page) {
throw new NotFoundException(`Page could not bet found`);
}
return page;
}
Is there a better way to address this issue?