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!