0

I'm currently trying to create the model using nestjs mongoose schema, and i want to convert the mongodb data from snake case to camel case in my schema layer like this:

export type CharacterModelDocument = HydratedDocument<CharacterModel>;

@Schema({ timestamps: {
    createdAt: 'created_at',
    updatedAt: 'updated_at',
  },
})
export class CharacterModel implements CharacterModelInterface {
  _id: Types.ObjectId;

  @Prop({
    required: true,
    trim: true,
    index: true,
    alias: 'display_name',
  })
  displayName: string;

  @Prop({
    alias: 'profile_image',
  })
  profileImage: string;

  //another field
}

export const CharacterModelSchema =
  SchemaFactory.createForClass(CharacterModel);

CharacterModelSchema.plugin(snakeToCamel); //Installed Plugin

with my plugin like this:

import { Schema } from 'mongoose';

// function to convert snake_case to camelCase
const toCamel = (str: string): string => {
  return str.replace(/[-_][a-z]/gi, ($1) => {
    return $1.toUpperCase().replace('-', '').replace('_', '');
  });
};

const isObject = (obj: any): boolean => {
  return (
    obj === Object(obj) && !Array.isArray(obj) && typeof obj !== 'function'
  );
};

// transform key into the object in camel case
const transformKeys = (obj: any): any => {
  if (isObject(obj)) {
    const n: any = {};

    Object.keys(obj).forEach((k) => {
      n[toCamel(k)] = transformKeys(obj[k]);
    });
    return n;
  } else if (Array.isArray(obj)) {
    return obj.map((i) => {
      return transformKeys(i);
    });
  }
  return obj;
};

// snake to camel case plugin
export function snakeToCamel(schema: Schema) {
  const transform = (doc: any, ret: any) => {
    return transformKeys(ret);
  };

  schema.set('toJSON', { transform });
  schema.set('toObject', { transform });
}

And when i get the data, everything it works like normally

{
  Id: {
    buffer: {
      //objectid
    }
  },
  profileImage: 'profile.jpg' //camel case,
  //other fields
  createdAt: {},
  updatedAt: {},
  _V: 0,
  displayName: 'character name' //camel case
}

but when i try to access the value inside display name by using the converted camel case (e.g, displayName), it returns undefined where actually they had a value inside it.

so do you guys knows how to solve this?

Thank you

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.