#Best Practice for Handling _id in a TypeScript Node.js App with MongoDB?

3 messages · Page 1 of 1 (latest)

obsidian pendant
#

When returning data from my TypeScript Node.js app using MongoDB, should I keep _id as it is, or map it to id in a DTO? Is it better to handle this in the Mongoose schema using a virtual field? What’s the best practice?

opaque vale
nova wadi
#

In my app I do this when sending away data

export function transformEntity<T>(entity: T): TransformedEntity<T> {
  const { _id, __v, ...restOfTheProperties } = entity as T & { _id: string; __v: number }
  return {
    id: _id,
    ...restOfTheProperties,
  }
}
@Schema({
  toJSON: {
    transform: (_doc, ret: Entity) => transformEntity<Entity>(ret),
  },
})