Typegoose and NestJS: The 'save' property is not found on this type

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?

Answer №1

 const modifyCategory = async (identifier: string, newCategory: string): Promise<Page> {
        const targetPage = await getPageDetailsById(identifier);
        targetPage.category = newCategory;
        saveModifiedPage(targetPage); // Implementing the solution
        return targetPage;
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The NestJs provider fails to inject and throws an error stating that this.iGalleryRepository.addImage is not a recognized function

I'm currently working on developing a NestJS TypeScript backend application that interacts with MySQL as its database, following the principles of clean architecture. My implementation includes JWT and Authorization features. However, I seem to be enc ...

Backdrop dimming the Material UI Modal

My modal is designed to display the status of a transaction on my website, but I'm facing an issue where the backdrop dimming effect is being applied over the modal. Instead of appearing white as intended, the modal ends up having a dark gray tint. I ...

What are the recommended guidelines for using TypeScript effectively?

When facing difficulties, I have an array with functions, such as: this._array = [handler, func, type] How should I declare this private property? 1. Array<any> 2. any[] 3. T[] 4. Array<T> What is the difference in these declarations? ...

What is the purpose of including an api folder in a Next.js application that is using MongoDB?

I am currently working on an e-commerce project using Next.js and MongoDB. I used the example project "with-mongodb-mongoose" from GitHub as a starting point (https://github.com/vercel/next.js/tree/canary/examples/with-mongodb-mongoose). Everything is func ...

Tips for uploading information and posting it on a different page with mongoDB and Node.js

I am looking to implement a feature on a website where data is submitted to MongoDB from one page, and then retrieved and displayed on another page. The technologies I am working with include node.js, express, Mongoose, and MongoDB. Currently, the data is ...

Guide on associating user IDs with user objects

I am currently working on adding a "pin this profile" functionality to my website. I have successfully gathered an array of user IDs for the profiles I want to pin, but I am facing difficulties with pushing these IDs to the top of the list of profiles. My ...

Understanding how to efficiently map through FontAwesome icons using React TypeScript and effectively showcase them on the frontend

I am in the process of developing a versatile component that allows me to input the href, target, and rel attributes, along with specifying the FontAwesome Icon I want to utilize. My goal is to be able to pass multiple icons into this list, which will then ...

Unexpected artifacts are being introduced to the build folder by the compiler

Currently, I am following the steps outlined in this Getting Started guide to set up the installation of tsoa. According to their instructions, I have created a routes.ts folder and placed it under /build: /build /routes.ts Next, in /src/app.tsx, I mak ...

Tips for extracting key values from an array of objects in Typescript

I am working with an array called studyTypes: const studyTypes = [ { value: "ENG", label: "ENG-RU", }, { value: "RU", label: "RU-ENG", }, ]; Additionally, I have a state variable set ...

Concealing forms within an Angular 5 application

I'm currently working on displaying the terms of use on the initial screen along with two buttons. If the user clicks the accept button, they will be directed to the authentication form. However, if they click refuse, the "Refused Terms" screen will a ...

Can someone explain how to implement document.querySelector in TypeScript within the Angular framework?

I am tackling the task of creating a login/register form that allows users to switch between the two forms with the click of a button. The goal is to only display one form at a time. Initially, I implemented this functionality in a basic HTML file and it w ...

Troubleshooting ion-radio loop error in Ionic 2

I am encountering an issue with the ion-radio component in Ionic 2. The problem is that when the component retrieves data from a service using HTTP and assigns it to the data property within the ngOnInit lifecycle hook, the radio buttons are not able to b ...

Drawing a real-time curve using Phaser 3

After reading the article at the following link, I am attempting to create a dynamic curve showing where a bullet intersects with the land in my game before firing. Any suggestions or ideas on how to achieve this would be greatly appreciated. Thank you. L ...

Angular is having trouble locating the module for my custom library

Trying to implement SSR in my angular application, but encountering an error when running npm run build:ssr. I've created my own library named @asfc/shared, which is bundled in the dist folder. ERROR in projects/asfc-web/src/environments/environment. ...

Acquiring information from file within component operation

When a user drags and drops a file, how can I retrieve it from the drop event? HTML file <div (drop)="drop($event)" > drop file here </div> TS file drop (event) { console.log(event.target.files.length); // I need to retrieve the file her ...

Utilize mapping to object and preserve type inference

I am currently developing a function that utilizes a map function to map objects. interface Dictionary<T> { [key: string]: T; } function objectMap<TValue, TResult>( obj: Dictionary<TValue>, valSelector: (val: TValue) => TResult ...

What is the best way to establish a relationship between two schemas in MongoDB utilizing Mongoose?

Consider the following two database schemas: User Role The User Schema includes fields for: username password roletype The Role Schema includes a field for: userType How can we establish a connection between these two schemas in Mongoose, so that whe ...

Issues with exporting function and interface have been identified

When exporting a function and type from the library in the convertToUpper.ts file, I have the following code: export function Sample() { console.log('sample') } export type IProp = { name: string age: number } The index.ts file in my lib ...

Utilizing TypeScript path aliases in a Create React App project with TypeScript and ESLint: A step-by-step guide

I utilized a template project found at https://github.com/kristijorgji/cra-ts-storybook-styled-components and made some enhancements. package.json has been updated as follows: { "name": "test", "version": "0.1.0" ...

Could it be possible for TypeScript inference to directly infer the value and omit the key in the process?

class A { state: B } class B { something: C } class C { a: string; b: boolean; } type MagicType = ... const c: MagicType<A> c.state.a = "123" c.state.b = true; Is it possible to achieve the mentioned functionality without altering the exi ...