我的后端服务器使用的是类型鹅和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;
}但这是解决这个问题的最好方法吗?
发布于 2021-06-26 16:18:50
async updatePageCategory(id: string, category: string): Promise<Page> {
const page = await this.getPageById(id);
page.category = category;
this.pageModel.save(page) // this is the solution
return page;
}https://stackoverflow.com/questions/64891788
复制相似问题