打字稿中的猫鼬静态方法

时间:2020-05-24 18:25:14

标签: typescript mongoose nestjs

我在mongoose应用程序中使用nestjs。在静态方法上,我卡住了。我在单独的文件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 };

并将其导入到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;

另外,为了调用我的架构,我创建了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;
}

问题是,当我尝试使用静态方法const getMessageForResponse = await this.messageModel.getMessageForResponseFunction(_id);时出现错误:

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

如何以及在何处声明此方法以将其称为静态方法?谢谢!

1 个答案:

答案 0 :(得分:0)

您不是用this.messageModel.statics.getMessageForResponseFunction()来称呼它吗?