【发布时间】:2021-03-01 15:28:47
【问题描述】:
我正在为我的后端服务器使用 typegoose 和 nestjs。我的pages.service.ts 文件中已经有一个函数,可以通过名为getPageById() 的ID 获取单个页面。当我尝试从我的 pages.services.ts 文件中的另一个函数调用此函数时,我通过 typescript 收到以下错误:
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;
}
但这是解决这个问题的最佳方法吗?
【问题讨论】:
-
是的,这似乎是解决它的最佳方法。我正在考虑使用
mongoose.Document扩展模型类,但这会导致不同类型的问题。 -
除此之外,您还可以像我在
export type PagelDocument = DocumentType<Page>;中所做的那样在模型中声明一个类型,并在需要时使用它。
标签: typescript mongoose nestjs typegoose