I am using typegoose and nestjs for my backend-server. I already have a function in my pages.service.ts file to get a single page by ID called getPageById(). When i try to call this function from another inside my pages.services.ts file, i get the following error by typescript:
Property 'save' does not exist on type 'page'
my page.model.ts file looks like this
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;
}
and my pages.service.ts file looks like this
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() // i get the error here
return page;
}
}
What do i need to get this working?
Update
I could fix the bug. I changed the return type to Promise<DocumentType<Page>> like this
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;
}
But is this the best way to solve this?