Home > Software design >  Extend Document class or & Document with Mongoose Schemas?
Extend Document class or & Document with Mongoose Schemas?

Time:10-26

I am using NestJS to write some backend code and fetch objects from MongoDB. The examples they offer in their documentation create a class annotated with @Schema() and then concatenate it with their built-in mongoose Document class.

@Schema()
export class Cat {
  @Prop()
  name: string;
}

export type CatDocument = Cat & Document;

export const CatSchema = SchemaFactory.createForClass(Cat);

I have seen other examples where the class simply extends Document, which seems more robust and simple.

export class Cat extends Document {
  @Prop()
  name: string;
}

Is there a difference between the two?

CodePudding user response:

The advantage of only creating a type is that you don't make your class/model dependent of Mongoose library. So in the future if you want to change your database (for some reason) or use another library to connect with Mongo, you won't need to refactor all the classes, that are the core of the application and shouldn't be changed frequently; you will only need to remove the types and adapt the code that uses it.

  • Related