我正在为我的后端服务器使用 typegoose 和 nestjs。我的pages.service.ts
文件中已经有一个函数可以按 ID 获取单个页面,称为getPageById()
. 当我尝试从pages.services.ts
文件中的另一个调用此函数时,打字稿出现以下错误:
Property 'save' does not exist on type 'page'
我的page.model.ts
文件看起来像这样
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;
}
我的pages.service.ts
文件看起来像这样
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;
}
}
我需要什么才能让这个工作?
更新
我可以修复错误。我将返回类型更改为Promise<DocumentType<Page>>
这样
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;
}
但这是解决这个问题的最好方法吗?