Exploring Typescript's Mongoose static methods

My nestjs application utilizes the mongoose library, but I am encountering an issue with a static method. I have defined my static method in a separate file named message.methods.ts:

import { Schema } from 'mongoose';

import { MessageForResponseDTO } from 'modules/room/dto/message-for-response.dto';

/*
  Types
*/
export type getMessageForResponseFunction = (
  _id: Schema.Types.ObjectId,
) => MessageForResponseDTO;

/*
  Methods
*/
const getMessageForResponse: getMessageForResponseFunction = function(
  _id: Schema.Types.ObjectId,
) {
  return this.findOne({ _id }).populate('user');
};

/*
  Export
*/
export const messageStaticMethods = { getMessageForResponse };

I have imported it into my schema located in message.schema.ts:

import { Schema } from 'mongoose';

import { messageStaticMethods } from './message.methods';

const MessageSchema = new Schema(
  {
    room: {
      type: Schema.Types.ObjectId,
      ref: 'Room',
      required: true,
    },
    user: {
      type: Schema.Types.ObjectId,
      ref: 'User',
      required: true,
    },
    message: {
      type: String,
      required: true,
      trim: true,
    },
    usersInMessage: [
      {
        type: Schema.Types.ObjectId,
        ref: 'User',
        required: false,
      },
    ],
  },
  { timestamps: true },
);

MessageSchema.statics = messageStaticMethods;

export default MessageSchema;

To facilitate calling my schema, I constructed message.model.ts:

import { Document, Schema } from 'mongoose';

export interface MessageModel extends Document {
  readonly room: Schema.Types.ObjectId;
  readonly user: Schema.Types.ObjectId;
  readonly message: string;
  readonly usersInMessage: Schema.Types.ObjectId[];

  // dates
  createdAt?: Date;
  updatedAt?: Date;
}

The challenge arises when attempting to use my static method with the code

const getMessageForResponse = await this.messageModel.getMessageForResponseFunction(_id);
, resulting in an error:

Property 'getMessageForResponseFunction' does not exist on type 'Model<MessageModel, {}>'.

Can someone please guide me on properly declaring and using this method as static? Thank you!

Answer №1

Why not simply utilize

this.messageModel.statics.getMessageForResponseFunction()
when calling it?

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

What methods do typescript libraries use to interpret types during runtime?

After compiling source code from TypeScript to JavaScript, type annotations are removed and it becomes impossible to verify the type of a variable at runtime. Despite this limitation, there exist TypeScript libraries that alter their behavior based on the ...

How to extract the values from multiple checkboxes in Angular version 10

app.component.html <form #x="ngForm" (ngSubmit)="submit()"> <div class="form-check form-check-inline"> <input [(ngModel)]="details.a" #a="ngModel" type="checkbox" va ...

What is the way to send custom properties to TypeScript in combination with StyledComponents?

Encountering an error while attempting to implement Styled Components 3 with TypeScript: TS2365: Operator '<' cannot be applied to types 'ThemedStyledFunction<{}, any, DetailedHTMLProps<TableHTMLAttributes<HTMLTableElement>, ...

What is the process for generating an array of objects using JavaScript?

I am struggling to create an array of objects using JavaScript and facing errors with new lines added where I need to split the messages and collect row numbers. The row numbers should be comma-separated if it is a repetitive error message. I found a solu ...

React Typescript encountering issues with Firebase integration

I am currently using a setup with React and TypeScript powered by Vite. My Firebase version is 9.15.0 This file contains my firebase.ts code: import { initializeApp } from "firebase/app"; import { getAuth, GoogleAuthProvider } from "fireba ...

Showing a Mat-dialog using a shared component

I have developed a system to trigger a modal window when a click event occurs on table elements. Each column value clicked should result in displaying different content within the dialog box. My goal is to create a single component for the dialog box that ...

Enhance your Javascript code performance by efficiently identifying IDs within a list and linking them to a tree structure

Looking for a way to improve the performance of the logic used for iterating over tree data and applying 'dataState' to 'FAILED' if there are matching error ids. interface IData { id: string; label: string; . value: string; expa ...

What steps should I take to ensure my paths in Ionic 4 Typescript are functioning properly?

Currently, I'm in the process of transitioning my Ionic 3 application to Ionic 4 with Typescript 3.1, but I'm facing challenges with the Typescript paths. Within my tsconfig.json, I have the following setup: "paths": { "@models": [ "src/mod ...

The regeneratorRuntime variable is undefined when running TypeScript code in a web environment

I recently experimented with Vue.js + TypeScript + Parcel, exploring the usage of async/await in my index.ts file. index.html <html> ... <body> <script src="index.ts"></script> </body> </html> index.ts console.log( ...

Styling with react-jss based on intricate conditionals

After experimenting with react-jss for a few weeks, I am faced with the challenge of styling components efficiently. With numerous conditionals in these components, I am striving to avoid creating an excess of new components that essentially share the same ...

Utilizing Typescript to troubleshoot linting issues

After running the TypeScript linter, I received the following error message: Do not use Function as a type. The Function type accepts any function-like value, providing no type safety when calling the function. This lack of specificity can lead to common ...

Resolving ES6 type conflicts while compiling TypeScript to Node.js

I seem to be facing some challenges with the TypeScript 2 type system when working with Node.js. Let me explain the situation: I am compiling a small Node.js Express server written in TypeScript to plain ES5 for running under Node 6.10.0 (target: ES5 in ...

Creating a moving marquee effect in Ionic

I am attempting to achieve a marquee effect in Ionic, where the text automatically scrolls across the screen. It functions smoothly on the web simulator but appears incredibly choppy and not smooth when loaded onto an iPhone. I am wondering if there is a s ...

Issue with RouterLink not recognizing QueryParams

I have encountered an issue where dynamically generated URLs with queryParams inside [routerLink] are breaking routes. For example: this.url = '/question/ask?details=1' <a [routerLink]="url"> {{ data.name }}</a> Upon mouseover, the ...

Inquiry about how TypeScript handles object property references when passed into functions

As a newcomer to TypeScript, I am exploring the creation of a range slider with dual handles using D3.js. I have developed a simple class for managing the slider objects: export class VerticalRangeSlider{ private sliderContainer: d3.Selection<SVGG ...

Receiving "this" as an undefined value within the TypeScript class

Currently developing a rest api using express.js, typescript, and typeorm. Initially thought the issue was with AppDataSource, but it seems to be functioning properly. Below is my controller class: import { RequestWithBody } from '@utils/types/reque ...

Having trouble installing npm package in Angular project

After cloning my project from GitLab, I encountered an issue while trying to install the NPM packages. When I ran npm install, an error popped up: https://i.stack.imgur.com/WNT5s.png Upon checking the log file, I found the following error message: 3060 ...

Unexpected behavior: Mongoose is storing a blank record even with a 'required' schema

I've built a Node.js application using Mongoose and Express to develop a RESTful API. I have set required fields in the Mongoose schema, but even when submitting an empty POST request through Postman, the API still creates empty records. Why is Mongoo ...

The typical toggle function may not function efficiently in conjunction with the setState() method

In my current project, I have a state that defines an interface like this: MyState { variableOne: string; variableTwo: boolean; variableThree: boolean; // ... } There's also a toggle function in the code: toggleFunction = (value: keyof MyS ...

Enhancing Custom Elements in JointJS with a Port

I followed the steps from the jointjs tutorial to create a custom element, which looks like this: CustomRect = joint.dia.Element.define('example.CustomRect', { attrs: { rect: { refX: 0, refY: 0, refWidth: '116', ...