mongodb 无法在响应中获取mongoose虚拟字段

k4emjkb1  于 2023-03-22  发布在  Go
关注(0)|答案(1)|浏览(114)

我有下面的模式与几个虚拟字段。我无法得到这些虚拟回响应:

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';

import mongoose from 'mongoose';
import { Sportclub } from './sportclub.schema';
export type SportEventDocument = SportEvent & mongoose.Document;

@Schema({ timestamps: true, toJSON: { virtuals: true } })
export class SportEvent {
  @Prop({ required: true })
  title: string;

  @Prop({ required: true })
  description: string;

  @Prop({
    required: true,
    min: 0,
    validate: {
      validator: (value: number) => {
        // Check if the value is a positive number
        return value >= 0;
      },
      message: 'Price must be a positive number',
    },
  })
  price: number;

  @Prop({ required: true })
  startDateAndTime: Date;

  @Prop({
    required: true,
    min: 0,
    validate: {
      validator: (value: number) => {
        // Check if the value is a positive number
        return value >= 0;
      },
      message: 'Duration must be a positive number',
    },
  })
  durationInMinutes: number;

  @Prop({
    required: true,
    min: 1,
    validate: {
      validator: (value: number) => {
        // Check if the value is a positive number greater than or equal to 1
        return value >= 1;
      },
      message:
        'Maximum number of participants must be a positive number greater than or equal to 1',
    },
  })
  maximumNumberOfParticipants: number;

  @Prop({
    required: false,
    default: [],
    type: [mongoose.Schema.Types.ObjectId],
    ref: 'User',
  })
  enrolledParticipants: mongoose.Schema.Types.ObjectId[];

  @Prop({ required: true })
  hostId: mongoose.Schema.Types.ObjectId;

  @Prop({ required: true })
  sportclub: Sportclub;
}

export const SportEventSchema = SchemaFactory.createForClass(SportEvent);

//virtuals
SportEventSchema.virtual('enrolledParticipantsCount').get(function () {
  return this.enrolledParticipants.length;
});

SportEventSchema.virtual('maximumIncome').get(function () {
  return this.maximumNumberOfParticipants * this.price;
});

SportEventSchema.virtual('currentIncome').get(function () {
  return this.enrolledParticipants.length * this.price;
});

SportEventSchema.virtual('isFull').get(function () {
  return this.enrolledParticipants.length >= this.maximumNumberOfParticipants;
});

我尝试使用以下方法检索API调用中的所有sportevents:

// get all sport events.
  async getAllSportEvents(): Promise<SportEvent[]> {
    console.log('get all sportevents service (api) called');
    try {
      const result: SportEvent[] = await this.sportEventModel
        .find()
        .lean({ virtuals: true });
      console.log(result);
      return result;
    } catch (error) {
      throw new HttpException(error.message, 400);
    }
  }

这是SportEvent的接口:

import { Sportclub } from './Sportclub';

export interface SportEvent {
  _id?: string;
  title: string;
  description: string;
  price: number;
  startDateAndTime: Date;
  durationInMinutes: number;
  maximumNumberOfParticipants: number;
  enrolledParticipants?: string[];
  hostId: string;
  sportclub: Sportclub;
  //virtuals
  enrolledParticipantsCount?: number;
  isFull?: boolean;
  maximumIncome?: number;
  currentIncome?: number;
}

响应不包含虚拟字段。我不知道为什么它不包含。有谁知道吗?

kx7yvsdv

kx7yvsdv1#

发现问题,这部分:.lean({ virtuals: true });不知何故仍然删除虚拟。我只是删除了这一行,现在它的工作。如果有人知道为什么,请告诉我。

相关问题