nestjstypegoose

Replace _id to id in NestJs + Typegoose


I use NestJs + Typegoose. How to replace _id to id in NestJs + Typegoose? I didn't find a clear example. I've tried something but without any results.

@modelOptions({
  schemaOptions: {
    collection: 'users',
  },
})
export class UserEntity {
  @prop()
  id?: string;

  @prop({ required: true })
  public email: string;

  @prop({ required: true })
  public password: string;

  @prop({ enum: UserRole, default: UserRole.User, type: String })
  public role: UserRole;

  @prop({ default: null })
  public subscription: string;
}
@Injectable()
export class UsersService {
  constructor(
    @InjectModel(UserEntity) private readonly userModel: ModelType<UserEntity>,
  ) {}

  getOneByEmail(email: string) {
    return from(
      this.userModel
        .findOne({ email })
        .select('-password')
        .lean(),
    );
  }
}

Solution

  • Another way to update the default _id to id is by overriding the toJSON method in the modelOptions decorator.

    @modelOptions({
        schemaOptions: {
            collection: 'Order',
            timestamps: true,
            toJSON: {
                transform: (doc: DocumentType<TicketClass>, ret) => {
                    delete ret.__v;
                    ret.id = ret._id;
                    delete ret._id;
                }
            }
        }
    })
    @plugin(AutoIncrementSimple, [{ field: 'version' }])
    class TicketClass {
    
        @prop({ required: true })
        public title!: string
    
        @prop({ required: true })
        public price!: number
    
        @prop({ default: 1 })
        public version?: number
    }
    
    
    export type TicketDocument = DocumentType<TicketClass>
    
    
    export const Ticket = getModelForClass(TicketClass);