Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR TYPESCRIPT

nestjs mongoose schema virtual

// user.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

export type UserDocument = User & Document;

@Schema({
  toJSON: { // use toObject for objects
    virtuals: true,
  }
})
export class User {
  @Prop({ type: String })
  first_name: string;
  
  @Prop({ type: String })
  last_name: string;
  
  full_name: string;
}

const UserSchema = SchemaFactory.createForClass(User);
UserSchema.virtual('full_name').get(function (this: UserDocument) {
  return `${this.first_name} ${this.last_name}`;
});
export { UserSchema }
 
PREVIOUS NEXT
Tagged: #nestjs #mongoose #schema #virtual
ADD COMMENT
Topic
Name
8+1 =